import type { PageServerLoad } from "./$types";
import { gql } from "graphql-request";
import { getGraphQLClient } from "$lib/api";

const LEADERBOARD_QUERY = gql`
  query Leaderboard($limit: Int, $offset: Int) {
    leaderboard(limit: $limit, offset: $offset) {
      user_id
      display_name
      avatar
      total_weighted_points
      total_raw_points
      recordings_count
      playbacks_count
      achievements_count
      rank
    }
  }
`;

export const load: PageServerLoad = async ({ fetch, url }) => {
  try {
    const limit = parseInt(url.searchParams.get("limit") || "100");
    const offset = parseInt(url.searchParams.get("offset") || "0");

    const client = getGraphQLClient(fetch);
    const data = await client.request<{
      leaderboard: {
        user_id: string;
        display_name: string | null;
        avatar: string | null;
        total_weighted_points: number | null;
        total_raw_points: number | null;
        recordings_count: number | null;
        playbacks_count: number | null;
        achievements_count: number | null;
        rank: number;
      }[];
    }>(LEADERBOARD_QUERY, { limit, offset });

    return {
      leaderboard: data.leaderboard || [],
      pagination: {
        limit,
        offset,
        hasMore: data.leaderboard?.length === limit,
      },
    };
  } catch (error) {
    console.error("Leaderboard load error:", error);
    return {
      leaderboard: [],
      pagination: {
        limit: 100,
        offset: 0,
        hasMore: false,
      },
    };
  }
};
