import { expect, tap } from '@git.zone/tstest/tapbundle';
import { OpnsenseConfigFlow, createOpnsenseDiscoveryDescriptor, type IOpnsenseSnapshot } from '../../ts/integrations/opnsense/index.js';

const snapshot: IOpnsenseSnapshot = {
  connected: true,
  router: { name: 'Snapshot Firewall', macAddress: 'AA:BB:CC:DD:EE:FF' },
  devices: [],
  interfaces: [],
  gateways: [],
  firewall: {},
  system: {},
  telemetry: {},
  services: [],
  vpn: {},
  sensors: {},
  switches: [],
};

tap.test('matches and validates manual local HTTPS OPNsense candidates', async () => {
  const descriptor = createOpnsenseDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({
    url: 'https://firewall.local:8443',
    name: 'OPNsense Firewall',
    model: 'OPNsense',
    macAddress: 'AA-BB-CC-DD-EE-FF',
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('opnsense');
  expect(result.candidate?.port).toEqual(8443);
  expect(result.normalizedDeviceId).toEqual('aa:bb:cc:dd:ee:ff');
  expect(result.candidate?.metadata?.verifySsl).toBeFalse();

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

tap.test('accepts snapshot-only setup and rejects non-HTTPS endpoints', async () => {
  const descriptor = createOpnsenseDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const snapshotResult = await matcher.matches({ snapshot }, {});
  const httpResult = await matcher.matches({ url: 'http://firewall.local', name: 'OPNsense' }, {});

  expect(snapshotResult.matched).toBeTrue();
  expect(snapshotResult.confidence).toEqual('certain');
  expect(httpResult.matched).toBeFalse();
  expect(httpResult.reason).toInclude('HTTPS');
});

tap.test('builds OPNsense config flow output without claiming live HTTP support', async () => {
  const flow = new OpnsenseConfigFlow();
  const step = await flow.start({ source: 'manual', host: 'firewall.local', metadata: { trackerInterfaces: ['LAN'] } }, {});
  const done = await step.submit!({ url: 'firewall.local', apiKey: 'key', apiSecret: 'secret', trackerInterfaces: 'LAN,WAN' });

  expect(done.kind).toEqual('done');
  expect(done.config?.url).toEqual('https://firewall.local');
  expect(done.config?.ssl).toBeTrue();
  expect(done.config?.verifySsl).toBeFalse();
  expect(done.config?.trackerInterfaces).toEqual(['LAN', 'WAN']);
  expect(done.config?.metadata?.liveHttpImplemented).toBeFalse();
});

export default tap.start();
