import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AranetClient, AranetConfigFlow, AranetIntegration, AranetMapper, createAranetDiscoveryDescriptor, type IAranetSnapshot } from '../../ts/integrations/aranet/index.js';

const rawData = {
  "co2": 530,
  "temperature": 20.5,
  "battery": 95
};

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

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

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

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

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

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

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

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

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

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