import { expect, tap } from '@git.zone/tstest/tapbundle';
import { SynologySrmConfigFlow, createSynologySrmDiscoveryDescriptor, type ISynologySrmSnapshot } from '../../ts/integrations/synology_srm/index.js';

const snapshot: ISynologySrmSnapshot = {
  connected: true,
  router: {
    name: 'RT6600ax',
    host: '192.168.1.1',
    port: 8001,
    ssl: true,
    macAddress: 'AA:BB:CC:DD:EE:FF',
  },
  system: {},
  network: {},
  interfaces: [],
  clients: [],
  traffic: {},
  sensors: {},
  switches: [],
  actions: [],
};

tap.test('matches and validates manual Synology SRM router entries', async () => {
  const descriptor = createSynologySrmDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({ host: '192.168.1.1', name: 'RT6600ax', model: 'RT6600ax', macAddress: 'AA-BB-CC-DD-EE-FF' }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('synology_srm');
  expect(result.candidate?.port).toEqual(8001);
  expect(result.normalizedDeviceId).toEqual('aa:bb:cc:dd:ee:ff');

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

tap.test('matches local SRM HTTP candidates and snapshot-only manual setup', async () => {
  const descriptor = createSynologySrmDiscoveryDescriptor();
  const httpResult = await descriptor.getMatchers()[1].matches({ url: 'https://router.local:8001/webman/index.cgi' }, {});
  const snapshotResult = await descriptor.getMatchers()[0].matches({ snapshot }, {});
  const unrelated = await descriptor.getMatchers()[1].matches({ url: 'http://example.local/status' }, {});

  expect(httpResult.matched).toBeTrue();
  expect(httpResult.candidate?.host).toEqual('router.local');
  expect(snapshotResult.matched).toBeTrue();
  expect(snapshotResult.confidence).toEqual('certain');
  expect(unrelated.matched).toBeFalse();
});

tap.test('creates config flow output with Home Assistant SRM defaults', async () => {
  const step = await new SynologySrmConfigFlow().start({ source: 'manual', host: '192.168.1.1', id: 'router', name: 'RT6600ax' }, {});
  const done = await step.submit!({ snapshotJson: JSON.stringify(snapshot) });

  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('192.168.1.1');
  expect(done.config?.port).toEqual(8001);
  expect(done.config?.ssl).toBeTrue();
  expect(done.config?.verifySsl).toBeFalse();
  expect(done.config?.username).toEqual('admin');
  expect(done.config?.metadata?.liveSrmApiImplemented).toBeFalse();
});

export default tap.start();
