import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AnelPwrctrlClient, AnelPwrctrlConfigFlow, AnelPwrctrlIntegration, AnelPwrctrlMapper, createAnelPwrctrlDiscoveryDescriptor, type IAnelPwrctrlSnapshot } from '../../ts/integrations/anel_pwrctrl/index.js';

const rawData = {
  "outlet_1": true,
  "outlet_2": false,
  "temperature": 29
};

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

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

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

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

tap.test('maps Anel NET-PwrCtrl raw snapshots to runtime devices and entities', async () => {
  const client = new AnelPwrctrlClient({ name: 'Anel NET-PwrCtrl Test', rawData });
  const snapshot = await client.getSnapshot();
  const devices = AnelPwrctrlMapper.toDevices(snapshot);
  const entities = AnelPwrctrlMapper.toEntities(snapshot);

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

tap.test('exposes Anel NET-PwrCtrl runtime services without fake live control', async () => {
  const runtime = await new AnelPwrctrlIntegration().setup({ name: 'Anel NET-PwrCtrl Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'anel_pwrctrl', service: 'status', target: {} });
  const snapshot = status.data as IAnelPwrctrlSnapshot;

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

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

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