import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AveaClient, AveaConfigFlow, AveaIntegration, AveaMapper, HomeAssistantAveaIntegration, createAveaDiscoveryDescriptor, type IAveaSnapshot } from '../../ts/integrations/avea/index.js';

const rawData = {
  "on": true,
  "brightness": 180,
  "battery": 73
};

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

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

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

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

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

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

tap.test('exposes Elgato Avea runtime services without fake live control', async () => {
  const integration = new AveaIntegration();
  expect(new HomeAssistantAveaIntegration().domain).toEqual('avea');
  expect(integration.status).toEqual('control-runtime');

  const runtime = await integration.setup({ name: 'Elgato Avea Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'avea', service: 'status', target: {} });
  const snapshot = status.data as IAveaSnapshot;

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

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

  const executorRuntime = await new AveaIntegration().setup({
    name: 'Elgato Avea Executor',
    rawData,
    commandExecutor: {
      execute: async (requestArg) => ({ success: true, data: { service: requestArg.service } }),
    },
  }, {});
  const executed = await executorRuntime.callService!({ domain: 'light', service: 'set_level', target: {} });
  expect(executed.success).toBeTrue();
  expect((executed.data as { service: string }).service).toEqual('set_level');
  await executorRuntime.destroy();
});

export default tap.start();
