import { expect, tap } from '@git.zone/tstest/tapbundle';
import { FreeboxConfigFlow, FreeboxMapper, createFreeboxDiscoveryDescriptor, type IFreeboxRawData } from '../../ts/integrations/freebox/index.js';

const rawData: Partial<IFreeboxRawData> = {
  systemConfig: {
    mac: 'F4:CA:E5:5C:EA:14',
    serial: '805400T144100853',
    firmware_version: '4.8.0',
    model_info: { pretty_name: 'Freebox Server', name: 'fbxgw1r' },
    sensors: [{ name: 'cpu', value: 55 }],
  },
  connectionStatus: { rate_down: 1234, rate_up: 321, media: 'ftth', state: 'up' },
  wifiConfig: { enabled: true },
};

tap.test('matches Freebox zeroconf records by Home Assistant manifest service type', async () => {
  const descriptor = createFreeboxDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'freebox-zeroconf-match');
  const match = await matcher!.matches({
    type: '_fbx-api._tcp.local.',
    name: 'Freebox Server',
    host: 'mafreebox.freebox.fr',
    port: 443,
    properties: {
      uid: 'freebox-uid',
      api_version: '6.0',
      api_base_url: '/api/',
      api_domain: 'example.fbxos.fr',
      device_type: 'FreeboxServer1,2',
      https_available: 'true',
      https_port: '443',
    },
  }, {});

  expect(match.matched).toBeTrue();
  expect(match.candidate?.integrationDomain).toEqual('freebox');
  expect(match.candidate?.host).toEqual('example.fbxos.fr');
  expect(match.candidate?.metadata?.serviceType).toEqual('_fbx-api._tcp.local.');
  expect(match.candidate?.metadata?.apiVersion).toEqual('v6');
});

tap.test('matches manual Freebox snapshots and creates config flow output', async () => {
  const snapshot = FreeboxMapper.toSnapshot({ config: { name: 'Snapshot Freebox' }, rawData, online: true, source: 'manual' });
  const matcher = createFreeboxDiscoveryDescriptor().getMatchers().find((matcherArg) => matcherArg.id === 'freebox-manual-match');
  const match = await matcher!.matches({ metadata: { snapshot } }, {});

  expect(match.matched).toBeTrue();
  expect(match.candidate?.metadata?.snapshot).toEqual(snapshot);

  const done = await (await new FreeboxConfigFlow().start(match.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.snapshot?.router.macAddress).toEqual('f4:ca:e5:5c:ea:14');
  expect(done.config?.host).toBeUndefined();
});

tap.test('rejects Freebox-looking candidates without a usable local source', async () => {
  const validation = await createFreeboxDiscoveryDescriptor().getValidators()[0].validate({
    source: 'manual',
    integrationDomain: 'freebox',
    name: 'Freebox without host',
  }, {});

  expect(validation.matched).toBeFalse();
  expect(validation.reason).toEqual('Freebox candidate lacks a host, injected client, snapshot, or raw data.');
});

export default tap.start();
