import { expect, tap } from '@git.zone/tstest/tapbundle';
import { ForkedDaapdMapper, type IForkedDaapdSnapshot } from '../../ts/integrations/forked_daapd/index.js';

const snapshot: IForkedDaapdSnapshot = {
  online: true,
  source: 'snapshot',
  updatedAt: '2026-01-01T00:00:00.000Z',
  server: {
    id: 'Living Room',
    name: 'Living Room',
    host: 'living-room.local',
    port: 3689,
    protocol: 'http',
    libraryName: 'Living Room',
    websocketPort: 3688,
  },
  player: {
    state: 'play',
    repeat: 'off',
    consume: false,
    shuffle: true,
    volume: 42,
    item_id: 10,
    item_length_ms: 180000,
    item_progress_ms: 30000,
  },
  queue: {
    version: 7,
    count: 1,
    items: [{
      id: 10,
      position: 0,
      title: 'Example Track',
      artist: 'Example Artist',
      album: 'Example Album',
      album_artist: 'Example Album Artist',
      track_number: 1,
      length_ms: 180000,
      media_kind: 'music',
      data_kind: 'file',
      uri: 'library:track:10',
      artwork_url: '/artwork/item/10',
    }],
  },
  outputs: [
    { id: '0', name: 'Computer', type: 'ALSA', selected: true, volume: 40 },
    { id: 'airplay-1', name: 'Kitchen', type: 'AirPlay', selected: false, volume: 25 },
  ],
  library: {
    pipes: [{ title: 'librespot-java', uri: 'spotify:pipe' }],
    playlists: [{ name: 'Favorites', uri: 'library:playlist:1' }],
  },
};

tap.test('maps OwnTone server and outputs to devices', async () => {
  const devices = ForkedDaapdMapper.toDevices(snapshot);
  const server = devices.find((deviceArg) => deviceArg.id === 'forked_daapd.server.living_room');
  const output = devices.find((deviceArg) => deviceArg.id === 'forked_daapd.output.living_room.airplay_1');

  expect(server?.online).toBeTrue();
  expect(server?.state.some((stateArg) => stateArg.featureId === 'playback' && stateArg.value === 'playing')).toBeTrue();
  expect(output?.model).toEqual('AirPlay');
});

tap.test('maps OwnTone media player state, sources and output zones', async () => {
  const entities = ForkedDaapdMapper.toEntities(snapshot);
  const server = entities.find((entityArg) => entityArg.id === 'media_player.living_room_owntone');
  const kitchen = entities.find((entityArg) => entityArg.id === 'media_player.living_room_owntone_kitchen');

  expect(server?.state).toEqual('playing');
  expect(server?.attributes?.volumeLevel).toEqual(0.42);
  expect(server?.attributes?.mediaTitle).toEqual('Example Track');
  expect(server?.attributes?.mediaImageUrl).toEqual('http://living-room.local:3689/artwork/item/10');
  expect(server?.attributes?.sourceList).toEqual(['Clear queue', 'Default (no pipe)', 'librespot-java (pipe)', 'Favorites (playlist)']);
  expect(kitchen?.state).toEqual('off');
  expect(kitchen?.attributes?.outputId).toEqual('airplay-1');
});

export default tap.start();
