import { expect, tap } from '@git.zone/tstest/tapbundle';
import { VeraClient, VeraConfigFlow, VeraIntegration, VeraMapper, createVeraDiscoveryDescriptor, type IVeraSnapshot } from '../../ts/integrations/vera/index.js';

const rawData = {
  "devices": 6,
  "scenes": 2,
  "armed": false
};

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

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

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

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

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

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

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

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

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

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