import { expect, tap } from '@git.zone/tstest/tapbundle';
import { ActiontecClient, ActiontecConfigFlow, ActiontecIntegration, ActiontecMapper, createActiontecDiscoveryDescriptor, type IActiontecSnapshot } from '../../ts/integrations/actiontec/index.js';

const rawData = {
  "clients": 12,
  "wan_up": true,
  "uptime": 45678
};

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

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

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

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

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

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

tap.test('exposes Actiontec runtime services without fake live control', async () => {
  const runtime = await new ActiontecIntegration().setup({ name: 'Actiontec Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'actiontec', service: 'status', target: {} });
  const snapshot = status.data as IActiontecSnapshot;

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

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

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