import { expect, tap } from '@git.zone/tstest/tapbundle';
import { UnifiprotectClient, UnifiprotectConfigFlow, UnifiprotectIntegration, UnifiprotectMapper, createUnifiprotectDiscoveryDescriptor, type IUnifiprotectSnapshot } from '../../ts/integrations/unifiprotect/index.js';

const rawData = {
  "cameras": 5,
  "recording": true,
  "events": 9
};

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

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

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

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

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

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

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

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

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

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