import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AlarmdecoderClient, AlarmdecoderConfigFlow, AlarmdecoderIntegration, AlarmdecoderMapper, createAlarmdecoderDiscoveryDescriptor, type IAlarmdecoderSnapshot } from '../../ts/integrations/alarmdecoder/index.js';

const rawData = {
  "armed": false,
  "fault": false,
  "zones": 8
};

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

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

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

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

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

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

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

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

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

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

export default tap.start();
