import { expect, tap } from '@git.zone/tstest/tapbundle';
import { UbusClient, UbusConfigFlow, UbusIntegration, UbusMapper, createUbusDiscoveryDescriptor, type IUbusSnapshot } from '../../ts/integrations/ubus/index.js';

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

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

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

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

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

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

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

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

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

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

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