import { error, redirect } from '@sveltejs/kit';
import { getAllSessions, getSession } from '$lib/server/sessionStore';
import { PLEB_BEATLEADER_ID } from '$lib/utils/plebsaber-utils';
import type { PageServerLoad } from './$types';

type StatsUser = {
  beatleaderId: string;
  name: string | null;
  avatar: string | null;
  country: string | null;
  rank: number | null;
  techPp: number | null;
  accPp: number | null;
  passPp: number | null;
  lastSeenAt: number;
  lastSeenIso: string;
};

type BeatLeaderPlayer = {
  id: string;
  name: string;
  avatar?: string;
  country?: string;
  rank?: number;
  techPp?: number;
  accPp?: number;
  passPp?: number;
};

async function fetchBeatLeaderProfile(playerId: string): Promise<BeatLeaderPlayer | null> {
  try {
    const response = await fetch(`https://api.beatleader.xyz/player/${playerId}`);
    if (!response.ok) return null;
    return (await response.json()) as BeatLeaderPlayer;
  } catch {
    return null;
  }
}

export const load: PageServerLoad = async ({ cookies }) => {
  const currentSession = getSession(cookies);
  if (!currentSession) {
    throw redirect(302, '/auth/beatleader/login?redirect_uri=%2Ftools%2Fstats');
  }

  if (currentSession.beatleaderId !== PLEB_BEATLEADER_ID) {
    throw error(403, 'Forbidden');
  }

  const sessions = getAllSessions();
  const aggregated = new Map<string, { session: typeof sessions[0] }>();

  for (const stored of sessions) {
    const existing = aggregated.get(stored.beatleaderId);
    if (!existing || stored.lastSeenAt > existing.session.lastSeenAt) {
      aggregated.set(stored.beatleaderId, { session: stored });
    }
  }

  // Fetch all player profiles in parallel
  const userPromises = Array.from(aggregated.values()).map(async ({ session }) => {
    const profile = await fetchBeatLeaderProfile(session.beatleaderId);
    return {
      beatleaderId: session.beatleaderId,
      name: profile?.name ?? session.name,
      avatar: profile?.avatar ?? session.avatar,
      country: profile?.country ?? null,
      rank: profile?.rank ?? null,
      techPp: profile?.techPp ?? null,
      accPp: profile?.accPp ?? null,
      passPp: profile?.passPp ?? null,
      lastSeenAt: session.lastSeenAt,
      lastSeenIso: new Date(session.lastSeenAt).toISOString()
    } satisfies StatsUser;
  });

  const users = (await Promise.all(userPromises)).sort((a, b) => b.lastSeenAt - a.lastSeenAt);

  return {
    users
  };
};

