/**
 * Server-queue-sync helpers: the 5-second debounce, the immediate flush,
 * the queue-id cap, and the radio-skip guard inside
 * `flushPlayQueuePosition`. Fake timers drive the debounce; mocks stand
 * in for `savePlayQueue`, the playerStore, and the playback-progress
 * snapshot.
 */
import type { QueueItemRef, Track } from './playerStoreTypes';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const { savePlayQueueMock, playerState, progressSnapshot, isSubsonicServerReachableMock } = vi.hoisted(() => ({
  savePlayQueueMock: vi.fn(async (_ids: string[], _currentId: string | undefined, _pos: number, _serverId: string) => undefined),
  isSubsonicServerReachableMock: vi.fn((_serverId: string) => true),
  playerState: {
    queueItems: [] as QueueItemRef[],
    currentTrack: null as Track | null,
    currentRadio: null as { id: string } | null,
  },
  progressSnapshot: { currentTime: 0, progress: 0, buffered: 0 },
}));

vi.mock('../api/subsonicPlayQueue', () => ({ savePlayQueue: savePlayQueueMock }));
vi.mock('../utils/network/subsonicNetworkGuard', () => ({
  isSubsonicServerReachable: (serverId: string) => isSubsonicServerReachableMock(serverId),
}));
vi.mock('../utils/playback/playbackServer', () => ({
  getPlaybackServerId: () => 'srv-a',
}));
vi.mock('./playerStore', () => ({
  usePlayerStore: { getState: () => playerState },
}));
vi.mock('./playbackProgress', () => ({
  getPlaybackProgressSnapshot: () => progressSnapshot,
}));

import {
  _resetQueueSyncForTest,
  flushPlayQueuePosition,
  flushQueueSyncToServer,
  getLastQueueHeartbeatAt,
  syncQueueToServer,
} from './queueSync';

function track(id: string): Track {
  return { id, title: id, artist: 'A', album: 'X', albumId: 'X', duration: 100 };
}

// Thin-state: sync helpers take queue refs.
function ref(id: string): QueueItemRef {
  return { serverId: 'srv-a', trackId: id };
}

beforeEach(() => {
  vi.useFakeTimers();
  vi.setSystemTime(new Date('2026-05-12T12:00:00Z'));
  isSubsonicServerReachableMock.mockReturnValue(true);
  savePlayQueueMock.mockClear();
  savePlayQueueMock.mockResolvedValue(undefined);
  playerState.queueItems = [];
  playerState.currentTrack = null;
  playerState.currentRadio = null;
  progressSnapshot.currentTime = 0;
});

afterEach(() => {
  _resetQueueSyncForTest();
  vi.useRealTimers();
});

describe('syncQueueToServer (debounced)', () => {
  const queue = [ref('a'), ref('b')];

  it('skips sync while the playback server is unreachable', () => {
    isSubsonicServerReachableMock.mockReturnValue(false);
    syncQueueToServer(queue, track('a'), 30);
    vi.advanceTimersByTime(5000);
    expect(savePlayQueueMock).not.toHaveBeenCalled();
  });

  it('does not fire before 5 s elapse', () => {
    syncQueueToServer(queue, track('a'), 30);
    vi.advanceTimersByTime(4999);
    expect(savePlayQueueMock).not.toHaveBeenCalled();
  });

  it('fires once after 5 s with id list + current id + position in ms', () => {
    syncQueueToServer(queue, track('a'), 30);
    vi.advanceTimersByTime(5000);
    expect(savePlayQueueMock).toHaveBeenCalledWith(['a', 'b'], 'a', 30000, 'srv-a');
  });

  it('cancels the previous timer when called again before fire', () => {
    syncQueueToServer(queue, track('a'), 10);
    vi.advanceTimersByTime(3000);
    syncQueueToServer([...queue, ref('c')], track('a'), 20);
    vi.advanceTimersByTime(5000);
    expect(savePlayQueueMock).toHaveBeenCalledTimes(1);
    expect(savePlayQueueMock).toHaveBeenCalledWith(['a', 'b', 'c'], 'a', 20000, 'srv-a');
  });

  it('caps the queue at 1000 ids', () => {
    const big = Array.from({ length: 1500 }, (_, i) => ref(`t${i}`));
    syncQueueToServer(big, track('t0'), 0);
    vi.advanceTimersByTime(5000);
    const ids = savePlayQueueMock.mock.calls[0][0] as string[];
    expect(ids.length).toBe(1000);
    expect(ids[0]).toBe('t0');
    expect(ids[999]).toBe('t999');
  });
});

describe('flushQueueSyncToServer (immediate)', () => {
  it('fires synchronously with no debounce', async () => {
    await flushQueueSyncToServer([ref('a')], track('a'), 12);
    expect(savePlayQueueMock).toHaveBeenCalledWith(['a'], 'a', 12000, 'srv-a');
  });

  it('cancels a pending debounced sync first', async () => {
    syncQueueToServer([ref('a')], track('a'), 30);
    await flushQueueSyncToServer([ref('a')], track('a'), 31);
    expect(savePlayQueueMock).toHaveBeenCalledTimes(1);
    // After the flush returns, advancing past the debounce should not fire again.
    vi.advanceTimersByTime(10_000);
    expect(savePlayQueueMock).toHaveBeenCalledTimes(1);
  });

  it('is a no-op when currentTrack is null', async () => {
    await flushQueueSyncToServer([ref('a')], null, 5);
    expect(savePlayQueueMock).not.toHaveBeenCalled();
  });

  it('is a no-op for an empty queue', async () => {
    await flushQueueSyncToServer([], track('a'), 5);
    expect(savePlayQueueMock).not.toHaveBeenCalled();
  });

  it('records the heartbeat timestamp', async () => {
    expect(getLastQueueHeartbeatAt()).toBe(0);
    await flushQueueSyncToServer([ref('a')], track('a'), 5);
    expect(getLastQueueHeartbeatAt()).toBe(Date.now());
  });
});

describe('flushPlayQueuePosition', () => {
  it('reads the current playerStore queue + playback-progress time', async () => {
    playerState.queueItems = [ref('a'), ref('b')];
    playerState.currentTrack = track('a');
    progressSnapshot.currentTime = 42;
    await flushPlayQueuePosition();
    expect(savePlayQueueMock).toHaveBeenCalledWith(['a', 'b'], 'a', 42000, 'srv-a');
  });

  it('is a no-op when a radio session is active', async () => {
    playerState.queueItems = [ref('a')];
    playerState.currentTrack = track('a');
    playerState.currentRadio = { id: 'radio-1' };
    await flushPlayQueuePosition();
    expect(savePlayQueueMock).not.toHaveBeenCalled();
  });
});
