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

tap.test('matches manual Modbus TCP entries', async () => {
  const descriptor = createModbusDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'modbus-manual-tcp-match');
  const result = await matcher!.matches({
    host: '192.168.1.50',
    port: 502,
    type: 'tcp',
    name: 'Heat pump Modbus',
    unitId: 2,
  }, {});
  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('modbus');
  expect(result.candidate?.port).toEqual(502);
  expect(result.candidate?.metadata?.unitId).toEqual(2);
});

tap.test('does not guess serial RTU ports', async () => {
  const descriptor = createModbusDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'modbus-manual-tcp-match');
  const result = await matcher!.matches({
    type: 'serial',
    host: '/dev/ttyUSB0',
    name: 'RS485 adapter',
  }, {});
  expect(result.matched).toBeFalse();
  expect(result.reason).toContain('Serial RTU');
});

tap.test('validates Modbus TCP candidates', async () => {
  const descriptor = createModbusDiscoveryDescriptor();
  const validator = descriptor.getValidators()[0];
  const result = await validator.validate({
    source: 'manual',
    integrationDomain: 'modbus',
    host: 'plc.local',
  }, {});
  expect(result.matched).toBeTrue();
  expect(result.candidate?.port).toEqual(502);
});

export default tap.start();
