import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AprilaireClient, AprilaireConfigFlow, AprilaireIntegration, AprilaireMapper, createAprilaireDiscoveryDescriptor, type IAprilaireSnapshot } from '../../ts/integrations/aprilaire/index.js';

const rawData = {
  "temperature": 20.9,
  "humidity": 38,
  "mode": "heat"
};

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

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

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

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

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

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

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

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

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

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

export default tap.start();
