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

tap.test('matches AirGradient zeroconf records', async () => {
  const descriptor = createAirgradientDiscoveryDescriptor();
  const mdnsMatcher = descriptor.getMatchers()[0];
  const result = await mdnsMatcher.matches({
    type: '_airgradient._tcp.local.',
    name: 'Living Room._airgradient._tcp.local.',
    host: 'airgradient-123456.local',
    port: 80,
    txt: {
      serialno: 'abcdef123456',
      model: 'I-9PSL',
      fw_ver: '3.1.2',
    },
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.confidence).toEqual('certain');
  expect(result.normalizedDeviceId).toEqual('abcdef123456');
  expect(result.candidate?.integrationDomain).toEqual('airgradient');
  expect(result.candidate?.metadata?.firmwareSupported).toBeTrue();
});

tap.test('matches manual AirGradient entries and validates supported firmware', async () => {
  const descriptor = createAirgradientDiscoveryDescriptor();
  const manualMatcher = descriptor.getMatchers()[1];
  const result = await manualMatcher.matches({
    host: '192.168.1.75',
    name: 'Living Room AirGradient',
    serialNumber: 'abcdef123456',
    firmwareVersion: '3.1.2',
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.port).toEqual(80);

  const validator = descriptor.getValidators()[0];
  const validated = await validator.validate(result.candidate!, {});
  expect(validated.matched).toBeTrue();
  expect(validated.confidence).toEqual('certain');
});

tap.test('rejects unsupported AirGradient firmware versions when known', async () => {
  const validator = createAirgradientDiscoveryDescriptor().getValidators()[0];
  const result = await validator.validate({
    source: 'mdns',
    integrationDomain: 'airgradient',
    host: 'airgradient-old.local',
    serialNumber: 'old123',
    metadata: {
      discoveryProtocol: 'zeroconf',
      firmwareVersion: '3.0.9',
    },
  }, {});

  expect(result.matched).toBeFalse();
  expect(result.reason).toContain('below the supported minimum');
});

export default tap.start();
