import { expect, tap } from '@git.zone/tstest/tapbundle';
import { Airtouch5Client, Airtouch5ConfigFlow, Airtouch5Integration, Airtouch5Mapper, createAirtouch5DiscoveryDescriptor, type IAirtouch5Snapshot } from '../../ts/integrations/airtouch5/index.js';

const rawData = {
  "zones": 7,
  "temperature": 22.2,
  "mode": "cool"
};

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

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

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

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

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

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

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

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

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

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