import { expect, tap } from '@git.zone/tstest/tapbundle';
import { WemoClient, WemoConfigFlow, WemoIntegration, WemoMapper, createWemoDiscoveryDescriptor, type IWemoSnapshot } from '../../ts/integrations/wemo/index.js';

const rawData = {
  "power": true,
  "signal": 76
};

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

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

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

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

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

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

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

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

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

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