import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AirvisualProClient, AirvisualProConfigFlow, AirvisualProIntegration, AirvisualProMapper, createAirvisualProDiscoveryDescriptor, type IAirvisualProSnapshot } from '../../ts/integrations/airvisual_pro/index.js';

const rawData = {
  "aqi": 34,
  "pm25": 6,
  "co2": 510
};

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

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

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

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

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

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

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

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

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

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