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

export const HISTORY_PAGE_SIZE = 50;

export type HistoryEvent = {
  id: string;
  played_at: string; // RFC3339
  track: TrackRef;
};

export type HistoryResponse = {
  events: HistoryEvent[];
  has_more: boolean;
};

// Exposed for direct testability (the createInfiniteQuery wrapper is harder
// to drive in unit tests without a full QueryClient harness).
export async function fetchHistoryPage(offset = 0): Promise<HistoryResponse> {
  return api.get<HistoryResponse>(
    `/api/me/history?offset=${offset}&limit=${HISTORY_PAGE_SIZE}`
  );
}

export function getNextPageParam(
  lastPage: HistoryResponse,
  _allPages: HistoryResponse[],
  lastPageParam: number
): number | undefined {
  return lastPage.has_more ? lastPageParam + HISTORY_PAGE_SIZE : undefined;
}

export function createHistoryQuery() {
  return createInfiniteQuery({
    queryKey: qk.history(),
    queryFn: ({ pageParam }) => fetchHistoryPage(pageParam as number),
    initialPageParam: 0,
    getNextPageParam: (lastPage, allPages, lastPageParam) =>
      getNextPageParam(lastPage, allPages, lastPageParam as number)
  });
}
