import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AtenPeClient, AtenPeConfigFlow, AtenPeIntegration, AtenPeMapper, createAtenPeDiscoveryDescriptor, type IAtenPeSnapshot } from '../../ts/integrations/aten_pe/index.js';

const rawData = {
  "outlet_1": true,
  "current": 1.4,
  "power": 320
};

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

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

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

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

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

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

tap.test('exposes ATEN Rack PDU runtime services without fake live control', async () => {
  const runtime = await new AtenPeIntegration().setup({ name: 'ATEN Rack PDU Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'aten_pe', service: 'status', target: {} });
  const snapshot = status.data as IAtenPeSnapshot;

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

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

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