import { expect, tap } from '@git.zone/tstest/tapbundle';
import { UnifiAccessClient, UnifiAccessConfigFlow, UnifiAccessIntegration, UnifiAccessMapper, createUnifiAccessDiscoveryDescriptor, type IUnifiAccessSnapshot } from '../../ts/integrations/unifi_access/index.js';

const rawData = {
  "doors": 2,
  "locked": true,
  "events": 4
};

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

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

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

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

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

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

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

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

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

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