import { expect, tap } from '@git.zone/tstest/tapbundle';
import { TplinkLteClient, TplinkLteConfigFlow, TplinkLteIntegration, TplinkLteMapper, createTplinkLteDiscoveryDescriptor, type ITplinkLteSnapshot } from '../../ts/integrations/tplink_lte/index.js';

const rawData = {
  "signal": 72,
  "connected": true,
  "sms_unread": 1
};

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

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

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

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

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

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

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

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

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

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