import { expect, tap } from '@git.zone/tstest/tapbundle';
import { IppConfigFlow, createIppDiscoveryDescriptor } from '../../ts/integrations/ipp/index.js';

tap.test('matches IPP and IPPS mDNS printer records', async () => {
  const descriptor = createIppDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'ipp-mdns-match');
  const result = await matcher!.matches({
    type: '_ipps._tcp.local.',
    name: 'Office Printer._ipps._tcp.local.',
    host: 'office-printer.local',
    port: 631,
    txt: {
      rp: 'ipp/print',
      UUID: 'printer-uuid-1',
      ty: 'HP Color LaserJet Pro',
      usb_MFG: 'HP',
      usb_MDL: 'Color LaserJet Pro',
    },
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.normalizedDeviceId).toEqual('printer-uuid-1');
  expect(result.candidate?.integrationDomain).toEqual('ipp');
  expect(result.candidate?.metadata?.basePath).toEqual('/ipp/print');
  expect(result.candidate?.metadata?.tls).toBeTrue();

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

tap.test('matches manual IPP URLs and carries defaults into config flow', async () => {
  const descriptor = createIppDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'ipp-manual-match');
  const match = await matcher!.matches({ host: 'ipps://printer.local:631/ipp/print', name: 'Manual Printer' }, {});
  expect(match.matched).toBeTrue();
  expect(match.candidate?.host).toEqual('printer.local');
  expect(match.candidate?.metadata?.basePath).toEqual('/ipp/print');
  expect(match.candidate?.metadata?.tls).toBeTrue();

  const step = await new IppConfigFlow().start(match.candidate!, {});
  const done = await step.submit!({ host: 'printer.local' });
  expect(done.kind).toEqual('done');
  expect(done.config?.port).toEqual(631);
  expect(done.config?.basePath).toEqual('/ipp/print');
  expect(done.config?.tls).toBeTrue();
});

tap.test('rejects IPP-looking candidates without a usable source', async () => {
  const descriptor = createIppDiscoveryDescriptor();
  const validator = descriptor.getValidators()[0];
  const validation = await validator.validate({ source: 'manual', integrationDomain: 'ipp', name: 'Printer without host' }, {});
  expect(validation.matched).toBeFalse();
  expect(validation.reason).toEqual('IPP candidate lacks host, snapshot, attributes, or client information.');
});

export default tap.start();
