import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AirthingsBleClient, AirthingsBleConfigFlow, AirthingsBleIntegration, AirthingsBleMapper, createAirthingsBleDiscoveryDescriptor, type IAirthingsBleSnapshot } from '../../ts/integrations/airthings_ble/index.js';

const rawData = {
  "radon": 42,
  "temperature": 20.8,
  "battery": 91
};

tap.test('matches manual Airthings BLE candidates and creates config flow output', async () => {
  const descriptor = createAirthingsBleDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'airthings_ble-manual-match');
  const result = await matcher!.matches({ host: 'airthings_ble.local', name: 'Airthings BLE', metadata: { rawData } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('airthings_ble');

  const validation = await descriptor.getValidators()[0].validate(result.candidate!, {});
  expect(validation.matched).toBeTrue();

  const done = await (await new AirthingsBleConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('airthings_ble.local');
});

tap.test('maps Airthings BLE raw snapshots to runtime devices and entities', async () => {
  const client = new AirthingsBleClient({ name: 'Airthings BLE Test', rawData });
  const snapshot = await client.getSnapshot();
  const devices = AirthingsBleMapper.toDevices(snapshot);
  const entities = AirthingsBleMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('airthings_ble');
  expect(entities.length > 0).toBeTrue();
});

tap.test('exposes Airthings BLE runtime services without fake live control', async () => {
  const runtime = await new AirthingsBleIntegration().setup({ name: 'Airthings BLE Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'airthings_ble', service: 'status', target: {} });
  const snapshot = status.data as IAirthingsBleSnapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Airthings BLE Runtime');

  const liveCommand = await runtime.callService!({ domain: 'airthings_ble', service: 'turn_on', target: {} });
  expect(liveCommand.success).toBeFalse();
  await runtime.destroy();

  const executorRuntime = await new AirthingsBleIntegration().setup({
    name: 'Airthings BLE Executor',
    rawData,
    commandExecutor: {
      execute: async (requestArg) => ({ success: true, data: { service: requestArg.service } }),
    },
  }, {});
  const executed = await executorRuntime.callService!({ domain: 'airthings_ble', service: 'turn_on', target: {} });
  expect(executed.success).toBeTrue();
  expect((executed.data as { service: string }).service).toEqual('turn_on');
  await executorRuntime.destroy();
});

export default tap.start();
