import { expect, tap } from '@git.zone/tstest/tapbundle';
import { TplinkOmadaClient, TplinkOmadaConfigFlow, TplinkOmadaIntegration, TplinkOmadaMapper, createTplinkOmadaDiscoveryDescriptor, type ITplinkOmadaSnapshot } from '../../ts/integrations/tplink_omada/index.js';

const rawData = {
  "clients": 34,
  "aps": 3,
  "connected": true
};

tap.test('matches manual TP-Link Omada candidates and creates config flow output', async () => {
  const descriptor = createTplinkOmadaDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'tplink_omada-manual-match');
  const result = await matcher!.matches({ host: 'tplink_omada.local', name: 'TP-Link Omada', metadata: { rawData } }, {});

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

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

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

tap.test('maps TP-Link Omada raw snapshots to runtime devices and entities', async () => {
  const client = new TplinkOmadaClient({ name: 'TP-Link Omada Test', rawData });
  const snapshot = await client.getSnapshot();
  const devices = TplinkOmadaMapper.toDevices(snapshot);
  const entities = TplinkOmadaMapper.toEntities(snapshot);

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

tap.test('exposes TP-Link Omada runtime services without fake live control', async () => {
  const runtime = await new TplinkOmadaIntegration().setup({ name: 'TP-Link Omada Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'tplink_omada', service: 'status', target: {} });
  const snapshot = status.data as ITplinkOmadaSnapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('TP-Link Omada Runtime');

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

  const executorRuntime = await new TplinkOmadaIntegration().setup({
    name: 'TP-Link Omada Executor',
    rawData,
    commandExecutor: {
      execute: async (requestArg) => ({ success: true, data: { service: requestArg.service } }),
    },
  }, {});
  const executed = await executorRuntime.callService!({ domain: 'tplink_omada', 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();
