import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AwairClient, AwairConfigFlow, AwairIntegration, AwairMapper, HomeAssistantAwairIntegration, createAwairDiscoveryDescriptor, type IAwairSnapshot } from '../../ts/integrations/awair/index.js';

const rawData = {
  "score": 89,
  "co2": 510,
  "pm25": 4
};

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

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

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

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

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

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

tap.test('exposes Awair read-only runtime services without fake live control', async () => {
  const integration = new AwairIntegration();
  expect(new HomeAssistantAwairIntegration().domain).toEqual('awair');
  expect(integration.status).toEqual('read-only-runtime');

  const runtime = await integration.setup({ name: 'Awair Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'awair', service: 'status', target: {} });
  const snapshot = status.data as IAwairSnapshot;

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

  const unsupported = await runtime.callService!({ domain: 'sensor', service: 'status', target: {} });
  expect(unsupported.success).toBeFalse();
  await runtime.destroy();
});

export default tap.start();
