import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AirzoneClient, AirzoneConfigFlow, AirzoneIntegration, AirzoneMapper, createAirzoneDiscoveryDescriptor, type IAirzoneSnapshot } from '../../ts/integrations/airzone/index.js';

const rawData = {
  "zones": 4,
  "temperature": 21.8,
  "mode": "auto"
};

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

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

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

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

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

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

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

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

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

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