import { expect, tap } from '@git.zone/tstest/tapbundle';
import { ArcamFmjIntegration, type IArcamFmjModeledCommand, type IArcamFmjSnapshot } from '../../ts/integrations/arcam_fmj/index.js';

const snapshot: IArcamFmjSnapshot = {
  deviceInfo: {
    name: 'Living Room Arcam',
    model: 'AVR450',
    uniqueId: 'arcam-abc123',
    apiModel: 'API450_SERIES',
  },
  zones: [{
    zone: 1,
    power: true,
    source: 'BD',
    available: true,
  }, {
    zone: 2,
    power: true,
    source: 'FM',
    available: true,
  }],
  online: true,
};

tap.test('models Arcam FMJ volume services through an explicit executor', async () => {
  const executed: IArcamFmjModeledCommand[] = [];
  const integration = new ArcamFmjIntegration();
  const runtime = await integration.setup({
    snapshot,
    commandExecutor: {
      execute: async (commandArg) => {
        executed.push(commandArg);
        return { accepted: true };
      },
    },
  }, {});

  const result = await runtime.callService!({
    domain: 'media_player',
    service: 'volume_set',
    target: { entityId: 'media_player.living_room_arcam_zone_2' },
    data: { volume_level: 0.25 },
  });

  expect(result.success).toBeTrue();
  expect(executed[0].zone).toEqual(2);
  expect(executed[0].commandCodeName).toEqual('VOLUME');
  expect(executed[0].data).toEqual([25]);
  expect(executed[0].responseExpected).toBeTrue();
});

tap.test('models Arcam FMJ source and power commands without pretending TCP success', async () => {
  const executed: IArcamFmjModeledCommand[] = [];
  const integration = new ArcamFmjIntegration();
  const runtimeWithExecutor = await integration.setup({
    snapshot,
    commandExecutor: {
      execute: async (commandArg) => {
        executed.push(commandArg);
      },
    },
  }, {});

  const sourceResult = await runtimeWithExecutor.callService!({
    domain: 'media_player',
    service: 'select_source',
    target: { entityId: 'media_player.living_room_arcam' },
    data: { source: 'BD' },
  });
  expect(sourceResult.success).toBeTrue();
  expect(executed[0].commandCodeName).toEqual('SIMULATE_RC5_IR_COMMAND');
  expect(executed[0].data).toEqual([16, 4]);
  expect(executed[0].usesRc5).toBeTrue();

  const runtimeWithoutExecutor = await integration.setup({ snapshot }, {});
  const turnOnResult = await runtimeWithoutExecutor.callService!({
    domain: 'media_player',
    service: 'turn_on',
    target: { entityId: 'media_player.living_room_arcam' },
  });
  expect(turnOnResult.success).toBeFalse();
  expect(turnOnResult.error).toContain('config.host or commandExecutor');
});

export default tap.start();
