import { expect, tap } from '@git.zone/tstest/tapbundle';
import { YoulessClient, YoulessConfigFlow, YoulessIntegration, YoulessMapper, createYoulessDiscoveryDescriptor, type IYoulessSnapshot } from '../../ts/integrations/youless/index.js';

const rawData = {
  "power": 342,
  "gas": 120.5,
  "net": false
};

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

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

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

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

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

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

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

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

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

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