import { getSession } from '../../lib/server/sessionStore';
import { PLEB_BEATLEADER_ID } from '../../lib/utils/plebsaber-utils';
import type { BeatLeaderPlayerProfile } from '../../lib/utils/plebsaber-utils';
import type { LayoutServerLoad } from './$types';

const PLAYER_ENDPOINT = 'https://api.beatleader.com/player/';

export const prerender = false;

export const load: LayoutServerLoad = async ({ cookies, fetch }) => {
  const session = getSession(cookies);

  let player: BeatLeaderPlayerProfile | null = null;
  let adminRank: number | null = null;
  let adminPlayer: BeatLeaderPlayerProfile | null = null;

  if (session) {
    try {
      const res = await fetch(`${PLAYER_ENDPOINT}${encodeURIComponent(session.beatleaderId)}?stats=true`);
      if (res.ok) {
        const data = (await res.json()) as Record<string, unknown>;
        const profile: BeatLeaderPlayerProfile = {
          id: typeof data.id === 'string' ? (data.id as string) : session.beatleaderId,
          name: typeof data.name === 'string' ? (data.name as string) : session.name ?? undefined,
          avatar: typeof data.avatar === 'string' ? (data.avatar as string) : session.avatar ?? null,
          country: typeof data.country === 'string' ? (data.country as string) : null,
          rank: typeof data.rank === 'number' ? (data.rank as number) : null,
          countryRank: typeof data.countryRank === 'number' ? (data.countryRank as number) : null,
          techPp: typeof data.techPp === 'number' ? (data.techPp as number) : null,
          accPp: typeof data.accPp === 'number' ? (data.accPp as number) : null,
          passPp: typeof data.passPp === 'number' ? (data.passPp as number) : null
        };
        player = profile;
        if (session.beatleaderId === PLEB_BEATLEADER_ID) {
          adminRank = typeof data.rank === 'number' ? (data.rank as number) : null;
          adminPlayer = profile;
        }
      }
    } catch (err) {
      console.error('Failed to fetch BeatLeader profile for tools layout', err);
    }
  }

  if (!adminPlayer || adminRank === null) {
    try {
      const adminRes = await fetch(`${PLAYER_ENDPOINT}${encodeURIComponent(PLEB_BEATLEADER_ID)}?stats=true`);
      if (adminRes.ok) {
        const adminData = (await adminRes.json()) as Record<string, unknown>;
        const rankValue = adminData?.rank;
        if (typeof rankValue === 'number') {
          adminRank = rankValue;
        }
        adminPlayer = {
          id: typeof adminData.id === 'string' ? (adminData.id as string) : PLEB_BEATLEADER_ID,
          name: typeof adminData.name === 'string' ? (adminData.name as string) : undefined,
          avatar: typeof adminData.avatar === 'string' ? (adminData.avatar as string) : null,
          country: typeof adminData.country === 'string' ? (adminData.country as string) : null,
          rank: typeof adminData.rank === 'number' ? (adminData.rank as number) : null,
          countryRank: typeof adminData.countryRank === 'number' ? (adminData.countryRank as number) : null,
          techPp: typeof adminData.techPp === 'number' ? (adminData.techPp as number) : null,
          accPp: typeof adminData.accPp === 'number' ? (adminData.accPp as number) : null,
          passPp: typeof adminData.passPp === 'number' ? (adminData.passPp as number) : null
        };
      }
    } catch (err) {
      console.error('Failed to fetch BeatLeader admin baseline', err);
    }
  }

  return { hasBeatLeaderOAuth: Boolean(session), player, adminRank, adminPlayer };
};

