import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AirqClient, AirqConfigFlow, AirqIntegration, AirqMapper, createAirqDiscoveryDescriptor, type IAirqSnapshot } from '../../ts/integrations/airq/index.js';

const rawData = {
  "co2": 620,
  "humidity": 44,
  "healthy": true
};

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

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

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

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

tap.test('maps air-Q raw snapshots to runtime devices and entities', async () => {
  const client = new AirqClient({ name: 'air-Q Test', rawData });
  const snapshot = await client.getSnapshot();
  const devices = AirqMapper.toDevices(snapshot);
  const entities = AirqMapper.toEntities(snapshot);

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

tap.test('exposes air-Q runtime services without fake live control', async () => {
  const runtime = await new AirqIntegration().setup({ name: 'air-Q Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'airq', service: 'status', target: {} });
  const snapshot = status.data as IAirqSnapshot;

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

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

  const executorRuntime = await new AirqIntegration().setup({
    name: 'air-Q Executor',
    rawData,
    commandExecutor: {
      execute: async (requestArg) => ({ success: true, data: { service: requestArg.service } }),
    },
  }, {});
  const executed = await executorRuntime.callService!({ domain: 'airq', 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();
