import { expect, tap } from '@git.zone/tstest/tapbundle';
import { YamahaClient, YamahaConfigFlow, YamahaIntegration, YamahaMapper, createYamahaDiscoveryDescriptor, type IYamahaSnapshot } from '../../ts/integrations/yamaha/index.js';

const rawData = {
  "power": true,
  "input": "AV1",
  "volume": -38
};

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

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

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

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

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

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

tap.test('exposes Yamaha Network Receivers runtime services without fake live control', async () => {
  const runtime = await new YamahaIntegration().setup({ name: 'Yamaha Network Receivers Runtime', rawData }, {});
  const status = await runtime.callService!({ domain: 'yamaha', service: 'status', target: {} });
  const snapshot = status.data as IYamahaSnapshot;

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

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

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