import { expect, tap } from '@git.zone/tstest/tapbundle';
import { WledClient, WledConfigFlow, WledIntegration, WledMapper, createWledDiscoveryDescriptor, type IWledSnapshot } from '../../ts/integrations/wled/index.js';

const rawData = {
  "on": true,
  "brightness": 128,
  "effect": "Solid"
};

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

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

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

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

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

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

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

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

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

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