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

tap.test('matches ESPHome native API mDNS records', async () => {
  const descriptor = createEsphomeDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({
    type: '_esphomelib._tcp.local.',
    name: 'kitchen_sensor._esphomelib._tcp.local.',
    host: 'kitchen-sensor.local',
    port: 6053,
    txt: {
      mac: 'aabbccddeeff',
      name: 'kitchen_sensor',
      friendly_name: 'Kitchen Sensor',
      api_encryption: 'Noise_NNpsk0_25519_ChaChaPoly_SHA256',
    },
  }, {});
  expect(result.matched).toBeTrue();
  expect(result.normalizedDeviceId).toEqual('aa:bb:cc:dd:ee:ff');
  expect(result.candidate?.host).toEqual('kitchen-sensor.local');
  expect(result.candidate?.port).toEqual(6053);
  expect(result.candidate?.metadata?.encryptionRequired).toBeTrue();
});

tap.test('matches new ESPHome mDNS service type and manual entries', async () => {
  const descriptor = createEsphomeDiscoveryDescriptor();
  const mdnsMatcher = descriptor.getMatchers()[0];
  const manualMatcher = descriptor.getMatchers()[1];
  const mdnsResult = await mdnsMatcher.matches({
    type: '_esphome._tcp.local.',
    name: 'garage_door._esphome._tcp.local.',
    hostname: 'garage-door.local.',
    port: 6053,
    properties: { friendly_name: 'Garage Door' },
  }, {});
  const manualResult = await manualMatcher.matches({
    host: 'garage-door.local',
    name: 'Garage Door',
  }, {});
  expect(mdnsResult.matched).toBeTrue();
  expect(mdnsResult.candidate?.name).toEqual('Garage Door');
  expect(manualResult.matched).toBeTrue();
  expect(manualResult.candidate?.port).toEqual(6053);
});

export default tap.start();
