import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AppleTvClient, AppleTvConfigFlow, AppleTvIntegration, AppleTvMapper, createAppleTvDiscoveryDescriptor, type IAppleTvSnapshot } from '../../ts/integrations/apple_tv/index.js';

const rawData = {
  "state": "playing",
  "app": "TV",
  "volume": 34
};

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

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

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

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

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

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

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

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

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

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