import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AirobotClient, AirobotConfigFlow, AirobotIntegration, AirobotMapper, createAirobotDiscoveryDescriptor, type IAirobotSnapshot } from '../../ts/integrations/airobot/index.js';

const rawData = {
  "fan_speed": 2,
  "co2": 640,
  "filter_alarm": false
};

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

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

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

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

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

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

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

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

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

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