import { createInfiniteQuery } from '@tanstack/svelte-query';
import { api } from './client';
import { qk } from './queries';
import type { AlbumRef, Page } from './types';

export const ALBUM_PAGE_SIZE = 50;

export async function listAlbumsAlpha(limit: number, offset: number): Promise<Page<AlbumRef>> {
  return api.get<Page<AlbumRef>>(`/api/library/albums?limit=${limit}&offset=${offset}`);
}

export function createAlbumsAlphaInfiniteQuery() {
  return createInfiniteQuery({
    queryKey: qk.albumsAlpha(),
    queryFn: ({ pageParam = 0 }) => listAlbumsAlpha(ALBUM_PAGE_SIZE, pageParam),
    initialPageParam: 0,
    getNextPageParam: (last) => {
      const loaded = last.offset + last.items.length;
      return loaded >= last.total ? undefined : loaded;
    }
  });
}
