import { expect, tap } from '@git.zone/tstest/tapbundle';
import { HomekitControllerConfigFlow, createHomekitControllerDiscoveryDescriptor } from '../../ts/integrations/homekit_controller/index.js';

tap.test('matches HomeKit mDNS records', async () => {
  const descriptor = createHomekitControllerDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({
    type: '_hap._tcp.local.',
    name: 'Desk Lamp._hap._tcp.local.',
    host: 'desk-lamp.local',
    port: 51826,
    txt: {
      id: 'AA:BB:CC:DD:EE:FF',
      md: 'Lamp 1',
      mf: 'Example Lighting',
      ci: '5',
      sf: '1',
      'c#': '2',
      's#': '1',
      pv: '1.1',
    },
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.normalizedDeviceId).toEqual('aa:bb:cc:dd:ee:ff');
  expect(result.candidate?.host).toEqual('desk-lamp.local');
  expect(result.candidate?.metadata?.categoryName).toEqual('Lightbulb');
  expect(result.candidate?.metadata?.paired).toEqual(false);
});

tap.test('validates HomeKit candidates by metadata', async () => {
  const descriptor = createHomekitControllerDiscoveryDescriptor();
  const validator = descriptor.getValidators()[0];
  const result = await validator.validate({
    source: 'manual',
    id: 'AA:BB:CC:DD:EE:FF',
    host: 'desk-lamp.local',
    metadata: { homekit: true, category: 5 },
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.confidence).toEqual('high');
});

tap.test('preserves manual HomeKit setup metadata for config flow', async () => {
  const descriptor = createHomekitControllerDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[1];
  const result = await matcher.matches({
    source: 'manual',
    id: 'AA:BB:CC:DD:EE:FF',
    name: 'Manual Lamp',
    host: 'manual-lamp.local',
    setupCode: '23456789',
    category: 5,
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.metadata?.setupCode).toEqual('23456789');

  const flow = new HomekitControllerConfigFlow();
  const step = await flow.start(result.candidate!, {});
  const done = await step.submit?.({});

  expect(done?.kind).toEqual('done');
  expect(done?.config?.setupCode).toEqual('234-56-789');
  expect(done?.config?.host).toEqual('manual-lamp.local');
  expect(done?.config?.id).toEqual('aa:bb:cc:dd:ee:ff');
});

tap.test('rejects generic candidates with non-HomeKit category metadata', async () => {
  const descriptor = createHomekitControllerDiscoveryDescriptor();
  const validator = descriptor.getValidators()[0];
  const result = await validator.validate({
    source: 'manual',
    id: 'generic-device',
    host: 'generic.local',
    metadata: { category: 5 },
  }, {});

  expect(result.matched).toEqual(false);
});

export default tap.start();
