import type { RequestHandler } from './$types';
import { createBeatSaverAPI } from '$lib/server/beatsaver';

export const GET: RequestHandler = async ({ fetch, url }) => {
  try {
    const api = createBeatSaverAPI(fetch);
    const useCacheParam = url.searchParams.get('cache');
    const useCache = useCacheParam === null ? true : useCacheParam !== 'false';
    const maxPagesParam = url.searchParams.get('maxPages');
    const maxPages = maxPagesParam ? Number(maxPagesParam) : undefined;
    const songs = await api.getCuratedSongs(useCache, { maxPages, tolerateErrors: true });
    return new Response(JSON.stringify({ songs }), {
      headers: { 'content-type': 'application/json' }
    });
  } catch (err) {
    // Log server-side for debugging
    console.error('GET /api/beatsaver/curated failed:', err);
    const message = err instanceof Error ? err.message : 'Unknown error';
    return new Response(JSON.stringify({ error: message }), { status: 500, headers: { 'content-type': 'application/json' } });
  }
};


