import { expect, tap } from '@git.zone/tstest/tapbundle';
import { Airtouch4Client, Airtouch4ConfigFlow, Airtouch4Integration, Airtouch4Mapper, createAirtouch4DiscoveryDescriptor, type IAirtouch4Snapshot } from '../../ts/integrations/airtouch4/index.js';

const rawData = {
  "zones": 6,
  "temperature": 23.1,
  "mode": "heat"
};

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

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

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

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

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

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

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

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

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

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