import { expect, tap } from '@git.zone/tstest/tapbundle';
import { ArestClient, ArestConfigFlow, ArestIntegration, ArestMapper, createArestDiscoveryDescriptor, type IArestSnapshot } from '../../ts/integrations/arest/index.js';

const rawData = {
  "relay": true,
  "temperature": 24.1,
  "online": true
};

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

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

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

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

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

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

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

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

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

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