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

tap.test('matches manual DSMR network entries', async () => {
  const descriptor = createDsmrDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({ host: 'p1-reader.local', port: 2001, name: 'DSMR P1 bridge', metadata: { dsmr: true, dsmrVersion: '5' } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('dsmr');
  expect(result.candidate?.metadata?.connectionType).toEqual('network');
  expect(result.candidate?.metadata?.liveValidation).toBeFalse();
});

tap.test('matches manual DSMR serial entries and validates candidates', async () => {
  const descriptor = createDsmrDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({ serialPort: '/dev/ttyUSB0', name: 'DSMR P1 cable', metadata: { p1: true } }, {});
  const validator = descriptor.getValidators()[0];
  const validation = await validator.validate(result.candidate!, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.metadata?.connectionType).toEqual('serial');
  expect(validation.matched).toBeTrue();
  expect(validation.reason).toContain('live communication is not assumed');
});

tap.test('config flow creates network config without claiming connection success', async () => {
  const flow = new DsmrConfigFlow();
  const step = await flow.start({ source: 'manual', id: 'p1-reader', host: 'p1-reader.local', port: 2001, metadata: { connectionType: 'network', dsmrVersion: '5' } }, {});
  const result = await step.submit!({ connectionType: 'network', host: 'p1-reader.local', port: 2001, dsmrVersion: '5', protocol: 'dsmr_protocol', liveRead: false });

  expect(result.kind).toEqual('done');
  expect(result.config?.connectionType).toEqual('network');
  expect(result.config?.connected).toBeFalse();
  expect(result.config?.liveRead).toBeFalse();
});

export default tap.start();
