import { expect, tap } from '@git.zone/tstest/tapbundle';
import { FoscamConfigFlow, createFoscamDiscoveryDescriptor } from '../../ts/integrations/foscam/index.js';

tap.test('matches manual Foscam host entries and configures the local CGI flow', async () => {
  const descriptor = createFoscamDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const match = await matcher.matches({ host: '192.168.1.40', name: 'Porch Foscam', stream: 'Sub', rtspPort: 554 }, {});

  expect(match.matched).toBeTrue();
  expect(match.candidate?.integrationDomain).toEqual('foscam');
  expect(match.candidate?.host).toEqual('192.168.1.40');
  expect(match.candidate?.port).toEqual(88);

  const validation = await descriptor.getValidators()[0].validate(match.candidate!, {});
  expect(validation.matched).toBeTrue();

  const flow = new FoscamConfigFlow();
  const step = await flow.start(match.candidate!, {});
  const done = await step.submit!({ username: 'admin', password: 'secret' });
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('192.168.1.40');
  expect(done.config?.port).toEqual(88);
  expect(done.config?.username).toEqual('admin');
  expect(done.config?.stream).toEqual('Sub');
  expect(done.config?.rtspPort).toEqual(554);
});

tap.test('matches local SSDP Foscam camera metadata', async () => {
  const descriptor = createFoscamDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[2];
  const match = await matcher.matches({
    manufacturer: 'Foscam',
    location: 'http://192.168.1.41:88/',
    upnp: {
      friendlyName: 'Garage Foscam',
      modelName: 'FI9821W',
      serialNumber: 'FOS123',
    },
  }, {});

  expect(match.matched).toBeTrue();
  expect(match.candidate?.host).toEqual('192.168.1.41');
  expect(match.candidate?.port).toEqual(88);
  expect(match.candidate?.manufacturer).toEqual('Foscam');
  expect(match.candidate?.model).toEqual('FI9821W');
});

export default tap.start();
