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

tap.test('matches manual Velbus serial entries', async () => {
  const descriptor = createVelbusDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'velbus-manual-match');
  const result = await matcher!.matches({
    connection: 'serial',
    serialPath: '/dev/ttyACM0',
    manufacturer: 'Velleman',
    model: 'Velbus USB interface',
    serialNumber: 'VBUS123',
  }, {});
  expect(result.matched).toBeTrue();
  expect(result.normalizedDeviceId).toEqual('VBUS123');
  expect(result.candidate?.integrationDomain).toEqual('velbus');
  expect(result.candidate?.metadata?.connection).toEqual('serial');
  expect(result.candidate?.metadata?.serialPath).toEqual('/dev/ttyACM0');
});

tap.test('matches manual Velbus TCP entries', async () => {
  const descriptor = createVelbusDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'velbus-manual-match');
  const result = await matcher!.matches({
    connection: 'tcp',
    host: '192.168.1.60',
    tls: true,
    password: 'secret',
    name: 'Velbus Signum',
  }, {});
  expect(result.matched).toBeTrue();
  expect(result.normalizedDeviceId).toEqual('tcp:192.168.1.60:27015');
  expect(result.candidate?.port).toEqual(27015);
  expect(result.candidate?.metadata?.dsn).toEqual('tls://secret@192.168.1.60:27015');
});

tap.test('matches manual Velbus TCP DSN entries', async () => {
  const descriptor = createVelbusDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'velbus-manual-match');
  const result = await matcher!.matches({
    connection: 'tcp',
    dsn: 'tls://secret@192.168.1.61:27015',
    model: 'Velbus TCP/IP interface',
  }, {});
  expect(result.matched).toBeTrue();
  expect(result.candidate?.host).toEqual('192.168.1.61');
  expect(result.candidate?.metadata?.password).toEqual('secret');
});

tap.test('validates Velbus candidates', async () => {
  const descriptor = createVelbusDiscoveryDescriptor();
  const validator = descriptor.getValidators()[0];
  const result = await validator.validate({
    source: 'manual',
    integrationDomain: 'velbus',
    host: 'velbus.local',
    manufacturer: 'Velleman',
    metadata: { connection: 'tcp' },
  }, {});
  expect(result.matched).toBeTrue();
  expect(result.candidate?.manufacturer).toEqual('Velleman');
});

export default tap.start();
