import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AdsClient, AdsConfigFlow, AdsIntegration, AdsMapper, createAdsDiscoveryDescriptor, type IAdsSnapshot } from '../../ts/integrations/ads/index.js';

const rawData = {
  "cycle_time": 12,
  "connected": true,
  "output_enabled": false
};

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

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

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

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

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

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

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

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

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

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