import { expect, tap } from '@git.zone/tstest/tapbundle';
import { BroadlinkConfigFlow, createBroadlinkDiscoveryDescriptor } from '../../ts/integrations/broadlink/index.js';

tap.test('matches Broadlink DHCP candidates by Home Assistant MAC prefix', async () => {
  const descriptor = createBroadlinkDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'broadlink-dhcp-match');
  const result = await matcher?.matches({
    ipAddress: '192.168.1.50',
    macAddress: '34:EA:34:B4:5D:2C',
    hostname: 'rm4-bedroom',
  }, {});
  expect(result?.matched).toBeTrue();
  expect(result?.candidate?.integrationDomain).toEqual('broadlink');
  expect(result?.candidate?.host).toEqual('192.168.1.50');
  expect(result?.candidate?.metadata?.discoveryProtocol).toEqual('dhcp');
});

tap.test('matches manual Broadlink snapshot and learned-code entries', async () => {
  const descriptor = createBroadlinkDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'broadlink-manual-match');
  const result = await matcher?.matches({
    host: '192.168.1.51',
    type: 'RM4PRO',
    macAddress: '34ea34b45d2d',
    codes: { television: { power: 'JgAcAB0dHB44HhweGx4cHR06HB0cHhwdHB8bHhwADQUAAAAAAAAAAAAAAAA=' } },
    switches: [{ name: 'Television', commandOn: 'JgAcAB0dHB44HhweGx4cHR06HB0cHhwdHB8bHhwADQUAAAAAAAAAAAAAAAA=' }],
  }, {});
  expect(result?.matched).toBeTrue();
  expect(result?.candidate?.metadata?.deviceType).toEqual('RM4PRO');
  expect(result?.candidate?.metadata?.codesConfigured).toBeTrue();
  expect(result?.candidate?.metadata?.customSwitchesConfigured).toBeTrue();
});

tap.test('builds Broadlink config from candidate and rejects invalid snapshots', async () => {
  const flow = new BroadlinkConfigFlow();
  const step = await flow.start({
    source: 'manual',
    integrationDomain: 'broadlink',
    id: '34:ea:34:b4:5d:2c',
    host: '192.168.1.52',
    macAddress: '34:ea:34:b4:5d:2c',
    model: 'RM4PRO',
    metadata: { deviceType: 'RM4PRO', devtype: 0x520b },
  }, {});

  const done = await step.submit?.({ host: '192.168.1.52', timeout: 7, name: 'Bedroom RM4', type: 'RM4PRO' });
  expect(done?.kind).toEqual('done');
  expect(done?.config?.host).toEqual('192.168.1.52');
  expect(done?.config?.timeout).toEqual(7);
  expect(done?.config?.type).toEqual('RM4PRO');

  const invalid = await step.submit?.({ host: '192.168.1.52', snapshotJson: '{"connected":true}' });
  expect(invalid?.kind).toEqual('error');
});

export default tap.start();
