import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AqualogicClient, AqualogicConfigFlow, AqualogicIntegration, AqualogicMapper, createAqualogicDiscoveryDescriptor, type IAqualogicSnapshot } from '../../ts/integrations/aqualogic/index.js';

const rawData = {
  "pump": true,
  "pool_temperature": 27,
  "heater": false
};

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

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

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

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

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

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

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

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

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

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