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

tap.test('matches manual Channels hosts and validates candidates', async () => {
  const descriptor = createChannelsDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({
    host: '192.168.1.51',
    name: 'Living Room Channels',
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.confidence).toEqual('high');
  expect(result.candidate?.integrationDomain).toEqual('channels');
  expect(result.candidate?.port).toEqual(57000);

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

tap.test('matches Channels HTTP API status payloads', async () => {
  const descriptor = createChannelsDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[1];
  const result = await matcher.matches({
    host: '192.168.1.52',
    path: '/api/status',
    status: {
      status: 'playing',
      muted: false,
      channel: { number: '35.1', name: 'Fox-HD' },
    },
  }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.metadata?.channelsApi).toBeTrue();
  expect((result.candidate?.metadata?.status as { status?: string }).status).toEqual('playing');
});

tap.test('creates config from a discovery candidate', async () => {
  const flow = new ChannelsConfigFlow();
  const step = await flow.start({
    source: 'manual',
    integrationDomain: 'channels',
    id: 'channels-living-room',
    host: '192.168.1.51',
    port: 57000,
    name: 'Living Room Channels',
  }, {});
  const done = await step.submit!({});

  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('192.168.1.51');
  expect(done.config?.port).toEqual(57000);
  expect(done.config?.name).toEqual('Living Room Channels');
  expect(done.config?.uniqueId).toEqual('channels-living-room');
});

tap.test('rejects unrelated manual entries without host or Channels metadata', async () => {
  const descriptor = createChannelsDiscoveryDescriptor();
  const matcher = descriptor.getMatchers()[0];
  const result = await matcher.matches({
    name: 'Office Printer',
    manufacturer: 'Printer Corp',
  }, {});

  expect(result.matched).toBeFalse();
});

export default tap.start();
