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

tap.test('matches Sony Bravia ScalarWebAPI SSDP records', async () => {
  const descriptor = createBraviatvDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({
    st: 'urn:schemas-sony-com:service:ScalarWebAPI:1',
    usn: 'uuid:bravia-udn-123::urn:schemas-sony-com:service:ScalarWebAPI:1',
    location: 'http://192.168.1.80:52323/dmr.xml',
    headers: {
      manufacturer: 'Sony Corporation',
    },
    upnp: {
      friendlyName: 'Living Room Bravia',
      modelName: 'XR-55A80J',
      X_ScalarWebAPI_DeviceInfo: {
        X_ScalarWebAPI_BaseURL: 'http://192.168.1.80/sony',
        X_ScalarWebAPI_ServiceList: {
          X_ScalarWebAPI_ServiceType: ['guide', 'system', 'audio', 'avContent', 'appControl', 'videoScreen'],
        },
      },
    },
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.host).toEqual('192.168.1.80');
  expect(result.normalizedDeviceId).toEqual('bravia-udn-123');
  expect((result.candidate?.metadata?.scalarWebApiServices as string[]).includes('videoScreen')).toBeTrue();
});

tap.test('matches Sony Bravia mDNS records', async () => {
  const descriptor = createBraviatvDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[1];
  const result = await matcher.matches({
    type: '_sonyapilib._tcp.local.',
    name: 'Living Room Bravia._sonyapilib._tcp.local.',
    host: 'living-room-bravia.local',
    port: 80,
    txt: {
      manufacturer: 'Sony Corporation',
      model: 'BRAVIA XR',
      cid: 'sony-cid-123',
    },
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.host).toEqual('living-room-bravia.local');
  expect(result.candidate?.port).toEqual(80);
  expect(result.normalizedDeviceId).toEqual('sony-cid-123');
});

tap.test('validates Sony Bravia candidates', async () => {
  const descriptor = createBraviatvDiscoveryDescriptor();
  const validator = descriptor.getValidators()[0];
  const result = await validator.validate({
    source: 'manual',
    integrationDomain: 'braviatv',
    host: '192.168.1.81',
    manufacturer: 'Sony',
    model: 'BRAVIA',
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.confidence).toEqual('high');
});

export default tap.start();
