import { expect, tap } from '@git.zone/tstest/tapbundle';
import { EmbyIntegration, EmbyMapper, type IEmbyCommandRequest, type IEmbySnapshot } from '../../ts/integrations/emby/index.js';

const snapshot: IEmbySnapshot = {
  server: {
    Id: 'server-1',
    ServerName: 'Home Emby',
    Version: '4.8.10.0',
    LocalAddress: 'http://192.168.1.30:8096',
  },
  online: true,
  updatedAt: '2026-05-05T12:00:00.000Z',
  source: 'manual',
  sessions: [
    {
      Id: 'session-1',
      UserName: 'phil',
      Client: 'Emby Theater',
      DeviceName: 'Living Room TV',
      DeviceId: 'device-1',
      ApplicationVersion: '4.8.10',
      IsActive: true,
      SupportsRemoteControl: true,
      SupportedCommands: ['Pause', 'Unpause', 'Stop', 'SetVolume'],
      LastPlaybackCheckIn: '2026-05-05T12:01:00.000Z',
      PlayState: {
        IsPaused: false,
        IsMuted: false,
        PositionTicks: 1800000000,
        VolumeLevel: 55,
      },
      NowPlayingItem: {
        Id: 'movie-1',
        Name: 'Example Movie',
        Type: 'Movie',
        RunTimeTicks: 72000000000,
        ImageTags: { Primary: 'tag-1' },
      },
    },
  ],
};

tap.test('maps active Emby sessions to media devices', async () => {
  const devices = EmbyMapper.toDevices(snapshot);
  expect(devices.some((deviceArg) => deviceArg.id === 'emby.server.server_1')).toBeTrue();
  const sessionDevice = devices.find((deviceArg) => deviceArg.id === 'emby.session.device_1');
  expect(sessionDevice?.name).toEqual('Living Room TV');
  expect(sessionDevice?.features.some((featureArg) => featureArg.id === 'remote_command')).toBeTrue();
  expect(sessionDevice?.state.some((stateArg) => stateArg.featureId === 'current_title' && stateArg.value === 'Example Movie')).toBeTrue();
});

tap.test('maps active Emby sessions to media player entities', async () => {
  const entities = EmbyMapper.toEntities(snapshot);
  const activity = entities.find((entityArg) => entityArg.id === 'sensor.home_emby_active_clients');
  const player = entities.find((entityArg) => entityArg.platform === 'media_player');
  expect(activity?.state).toEqual(1);
  expect(player?.id).toEqual('media_player.living_room_tv');
  expect(player?.state).toEqual('playing');
  expect(player?.attributes?.volumeLevel).toEqual(0.55);
  expect(player?.attributes?.mediaContentType).toEqual('movie');
  expect(player?.attributes?.mediaDuration).toEqual(7200);
  expect(player?.attributes?.mediaPosition).toEqual(180);
  expect(player?.attributes?.mediaImageUrl).toEqual('http://192.168.1.30:8096/Items/movie-1/Images/Primary?tag=tag-1');
});

tap.test('runtime dispatches Emby media commands through commandExecutor', async () => {
  const commands: IEmbyCommandRequest[] = [];
  const integration = new EmbyIntegration();
  const runtime = await integration.setup({
    snapshot,
    commandExecutor: {
      async execute(commandArg) {
        commands.push(commandArg);
        return { ok: true };
      },
    },
  }, {});

  const pause = await runtime.callService!({ domain: 'media_player', service: 'media_pause', target: { entityId: 'media_player.living_room_tv' }, data: {} });
  const remote = await runtime.callService!({ domain: 'remote', service: 'send_command', target: { deviceId: 'emby.session.device_1' }, data: { command: 'ToggleFullscreen' } });

  expect(pause.success).toBeTrue();
  expect(remote.success).toBeTrue();
  expect(commands[0]).toMatchObject({ action: 'playstate', sessionId: 'session-1', command: 'Pause' });
  expect(commands[1]).toMatchObject({ action: 'general_command', sessionId: 'session-1', command: 'ToggleFullscreen' });
});

tap.test('runtime refuses fake control for static snapshots without a command path', async () => {
  const integration = new EmbyIntegration();
  const runtime = await integration.setup({ snapshot }, {});
  const result = await runtime.callService!({ domain: 'media_player', service: 'media_pause', target: { entityId: 'media_player.living_room_tv' }, data: {} });
  expect(result.success).toBeFalse();
  expect(result.error).toInclude('Static snapshots/manual data are read-only');
});

export default tap.start();
