import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AdaxClient, AdaxConfigFlow, AdaxIntegration, AdaxMapper, createAdaxDiscoveryDescriptor, type IAdaxSnapshot } from '../../ts/integrations/adax/index.js';

const rawData = {
  "temperature": 21.5,
  "target_temperature": 22,
  "heating": true
};

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

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

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

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

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

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

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

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

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

  const executorRuntime = await new AdaxIntegration().setup({
    name: 'Adax Executor',
    rawData,
    commandExecutor: {
      execute: async (requestArg) => ({ success: true, data: { service: requestArg.service } }),
    },
  }, {});
  const executed = await executorRuntime.callService!({ domain: 'adax', service: 'set_temperature', target: {} });
  expect(executed.success).toBeTrue();
  expect((executed.data as { service: string }).service).toEqual('set_temperature');
  await executorRuntime.destroy();
});

export default tap.start();
