import { expect, tap } from '@git.zone/tstest/tapbundle';
import { UpcConnectClient, UpcConnectConfigFlow, UpcConnectIntegration, UpcConnectMapper, createUpcConnectDiscoveryDescriptor, type IUpcConnectSnapshot } from '../../ts/integrations/upc_connect/index.js';

const rawData = {
  "clients": 11,
  "wan_up": true,
  "wifi_enabled": true
};

tap.test('matches manual UPC Connect Box candidates and creates config flow output', async () => {
  const descriptor = createUpcConnectDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'upc_connect-manual-match');
  const result = await matcher!.matches({ host: 'upc_connect.local', name: 'UPC Connect Box', metadata: { rawData } }, {});

  expect(result.matched).toBeTrue();
  expect(result.candidate?.integrationDomain).toEqual('upc_connect');

  const validation = await descriptor.getValidators()[0].validate(result.candidate!, {});
  expect(validation.matched).toBeTrue();

  const done = await (await new UpcConnectConfigFlow().start(result.candidate!, {})).submit!({});
  expect(done.kind).toEqual('done');
  expect(done.config?.host).toEqual('upc_connect.local');
});

tap.test('maps UPC Connect Box raw snapshots to runtime devices and entities', async () => {
  const client = new UpcConnectClient({ name: 'UPC Connect Box Test', rawData });
  const snapshot = await client.getSnapshot();
  const devices = UpcConnectMapper.toDevices(snapshot);
  const entities = UpcConnectMapper.toEntities(snapshot);

  expect(snapshot.online).toBeTrue();
  expect(snapshot.source).toEqual('manual');
  expect(devices[0].integrationDomain).toEqual('upc_connect');
  expect(entities.length > 0).toBeTrue();
});

tap.test('exposes UPC Connect Box runtime services without fake live control', async () => {
  const runtime = await new UpcConnectIntegration().setup({ name: 'UPC Connect Box Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'upc_connect', service: 'status', target: {} });
  const snapshot = status.data as IUpcConnectSnapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('UPC Connect Box Runtime');

  const liveCommand = await runtime.callService!({ domain: 'upc_connect', service: 'turn_on', target: {} });
  expect(liveCommand.success).toBeFalse();
  await runtime.destroy();

  const executorRuntime = await new UpcConnectIntegration().setup({
    name: 'UPC Connect Box Executor',
    rawData,
    commandExecutor: {
      execute: async (requestArg) => ({ success: true, data: { service: requestArg.service } }),
    },
  }, {});
  const executed = await executorRuntime.callService!({ domain: 'upc_connect', service: 'turn_on', target: {} });
  expect(executed.success).toBeTrue();
  expect((executed.data as { service: string }).service).toEqual('turn_on');
  await executorRuntime.destroy();
});

export default tap.start();
