import { createBeatSaverAPI, type MapDetailWithOrder, type PlaylistPage } from '$lib/server/beatsaver';
import { error, json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';

const PAGE_SIZE = 12;

export const GET: RequestHandler = async ({ url, fetch }) => {
  const idParam = url.searchParams.get('id');
  if (!idParam) {
    throw error(400, 'Missing playlist id');
  }

  const offsetParam = Number.parseInt(url.searchParams.get('offset') ?? '0', 10);
  const offset = Number.isFinite(offsetParam) && offsetParam >= 0 ? offsetParam : 0;
  const api = createBeatSaverAPI(fetch);
  try {
    const detail = (await api.getPlaylistDetail(idParam, { page: 0 })) as PlaylistPage;
    const maps = Array.isArray(detail?.maps) ? detail.maps : [];

    const totalCount = detail?.playlist?.stats?.totalMaps ?? maps.length;
    const slice = maps.slice(offset, offset + PAGE_SIZE) as MapDetailWithOrder[];

    return json({
      playlist: detail?.playlist ?? null,
      maps: slice,
      offset,
      page: Math.floor(offset / PAGE_SIZE),
      pageSize: PAGE_SIZE,
      totalCount
    });
  } catch (err) {
    console.error('Failed to load playlist detail', idParam, err);
    throw error(502, 'Failed to load playlist detail');
  }
};


