import { afterEach, describe, expect, it, vi } from 'vitest';
import { getLibraryBrowseItems } from './libraryBrowse';

function jsonResponse(body: unknown, status = 200): Response {
  return new Response(JSON.stringify(body), {
    headers: { 'Content-Type': 'application/json' },
    status
  });
}

function browseUrl(fetchMock: ReturnType<typeof vi.spyOn>): URL {
  return new URL(String(fetchMock.mock.calls[0][0]), 'http://localhost');
}

describe('getLibraryBrowseItems', () => {
  afterEach(() => {
    vi.restoreAllMocks();
  });

  it('maps the paging/library/mediaType params into the query string', async () => {
    const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ page: [], totalCount: 0 }));

    await getLibraryBrowseItems({
      query: 'star',
      libraryId: 5,
      mediaType: 'TelevisionShow',
      pageNum: 2,
      pageSize: 25
    });

    const url = browseUrl(fetchMock);
    expect(url.pathname).toBe('/api/v1/library/browse');
    expect(url.searchParams.get('query')).toBe('star');
    expect(url.searchParams.get('libraryId')).toBe('5');
    expect(url.searchParams.get('mediaType')).toBe('TelevisionShow');
    expect(url.searchParams.get('pageNum')).toBe('2');
    expect(url.searchParams.get('pageSize')).toBe('25');
    expect(url.searchParams.has('parentId')).toBe(false);
  });

  it('sends parentId to scope seasons to a specific show', async () => {
    const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ page: [], totalCount: 0 }));

    await getLibraryBrowseItems({ mediaType: 'TelevisionSeason', parentId: 42, pageSize: 100 });

    const url = browseUrl(fetchMock);
    expect(url.searchParams.get('mediaType')).toBe('TelevisionSeason');
    expect(url.searchParams.get('parentId')).toBe('42');
  });

  it('omits parentId when it is not provided', async () => {
    const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ page: [], totalCount: 0 }));

    await getLibraryBrowseItems({ mediaType: 'Movie' });

    expect(browseUrl(fetchMock).searchParams.has('parentId')).toBe(false);
  });
});
