import { ApiError, request } from './client';
import type { components } from './generated/v1';

export type LibraryBrowseItem = components['schemas']['LibraryBrowseItemResponseModel'];
export type LibraryBrowseMediaType = components['schemas']['LibraryBrowseMediaType'];
export type PagedLibraryBrowseItems = components['schemas']['PagedLibraryBrowseItemsResponseModel'];

export interface GetLibraryBrowseItemsParams {
  libraryId?: number;
  mediaType?: LibraryBrowseMediaType;
  pageNum?: number;
  pageSize?: number;
  // Only meaningful with mediaType 'TelevisionSeason': filters seasons to the given show id.
  parentId?: number;
  query?: string;
}

export function getLibraryBrowseItems(params: GetLibraryBrowseItemsParams = {}): Promise<PagedLibraryBrowseItems> {
  const searchParams = new URLSearchParams();

  if (params.query) {
    searchParams.set('query', params.query);
  }

  if (params.libraryId != null) {
    searchParams.set('libraryId', String(params.libraryId));
  }

  if (params.mediaType) {
    searchParams.set('mediaType', params.mediaType);
  }

  if (params.pageNum != null) {
    searchParams.set('pageNum', String(params.pageNum));
  }

  if (params.pageSize != null) {
    searchParams.set('pageSize', String(params.pageSize));
  }

  if (params.parentId != null) {
    searchParams.set('parentId', String(params.parentId));
  }

  const queryString = searchParams.toString();

  return request<PagedLibraryBrowseItems>(`/api/v1/library/browse${queryString ? `?${queryString}` : ''}`);
}

export function messageFromLibraryBrowseError(error: unknown, fallback = 'Unable to load library items'): string {
  if (error instanceof ApiError) {
    return error.detail ?? error.message;
  }

  if (error instanceof Error) {
    return error.message;
  }

  return fallback;
}
