import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AcmedaClient, AcmedaConfigFlow, AcmedaIntegration, AcmedaMapper, createAcmedaDiscoveryDescriptor, type IAcmedaSnapshot } from '../../ts/integrations/acmeda/index.js';

const rawData = {
  "position": 55,
  "moving": false,
  "rooms": 3
};

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

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

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

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

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

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

tap.test('exposes Rollease Acmeda Automate runtime services without fake live control', async () => {
  const runtime = await new AcmedaIntegration().setup({ name: 'Rollease Acmeda Automate Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'acmeda', service: 'status', target: {} });
  const snapshot = status.data as IAcmedaSnapshot;

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

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

  const executorRuntime = await new AcmedaIntegration().setup({
    name: 'Rollease Acmeda Automate Executor',
    rawData,
    commandExecutor: {
      execute: async (requestArg) => ({ success: true, data: { service: requestArg.service } }),
    },
  }, {});
  const executed = await executorRuntime.callService!({ domain: 'acmeda', service: 'open_cover', target: {} });
  expect(executed.success).toBeTrue();
  expect((executed.data as { service: string }).service).toEqual('open_cover');
  await executorRuntime.destroy();
});

export default tap.start();
