import { expect, tap } from '@git.zone/tstest/tapbundle';
import { AnthemavClient, AnthemavConfigFlow, AnthemavIntegration, AnthemavMapper, createAnthemavDiscoveryDescriptor, type IAnthemavSnapshot } from '../../ts/integrations/anthemav/index.js';

const rawData = {
  "power": true,
  "input": "HDMI1",
  "volume": -34
};

tap.test('matches manual Anthem A/V Receivers candidates and creates config flow output', async () => {
  const descriptor = createAnthemavDiscoveryDescriptor();
  const matcher = descriptor.getMatchers().find((matcherArg) => matcherArg.id === 'anthemav-manual-match');
  const result = await matcher!.matches({ host: 'anthemav.local', name: 'Anthem A/V Receivers', metadata: { rawData } }, {});

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

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

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

tap.test('maps Anthem A/V Receivers raw snapshots to runtime devices and entities', async () => {
  const client = new AnthemavClient({ name: 'Anthem A/V Receivers Test', rawData });
  const snapshot = await client.getSnapshot();
  const devices = AnthemavMapper.toDevices(snapshot);
  const entities = AnthemavMapper.toEntities(snapshot);

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

tap.test('exposes Anthem A/V Receivers runtime services without fake live control', async () => {
  const runtime = await new AnthemavIntegration().setup({ name: 'Anthem A/V Receivers Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'anthemav', service: 'status', target: {} });
  const snapshot = status.data as IAnthemavSnapshot;

  expect(status.success).toBeTrue();
  expect(snapshot.online).toBeTrue();
  expect((await runtime.devices())[0].name).toEqual('Anthem A/V Receivers Runtime');

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

  const executorRuntime = await new AnthemavIntegration().setup({
    name: 'Anthem A/V Receivers Executor',
    rawData,
    commandExecutor: {
      execute: async (requestArg) => ({ success: true, data: { service: requestArg.service } }),
    },
  }, {});
  const executed = await executorRuntime.callService!({ domain: 'anthemav', 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();
