import type { RequestHandler } from '@sveltejs/kit';
import { consumeAndValidateState, exchangeCodeForTokens, setTokens, clearTokens, consumeRedirectCookie, getValidAccessToken } from '$lib/server/beatleaderAuth';

export const GET: RequestHandler = async ({ url, cookies }) => {
  const code = url.searchParams.get('code');
  const state = url.searchParams.get('state');

  if (!code) {
    return new Response('Missing code', { status: 400 });
  }

  if (!consumeAndValidateState(cookies, state)) {
    return new Response('Invalid state', { status: 400 });
  }

  const tokenData = await exchangeCodeForTokens(url.origin, code);
  if (!tokenData || !tokenData.access_token) {
    clearTokens(cookies);
    return new Response('Token exchange failed', { status: 400 });
  }

  setTokens(cookies, tokenData);

  // Best-effort: enable ShowAllRatings so unranked star ratings are visible for supporters
  try {
    const tok = await getValidAccessToken(cookies);
    if (tok) {
      const enableUrl = new URL('https://api.beatleader.com/user/profile');
      enableUrl.searchParams.set('showAllRatings', 'true');
      await fetch(enableUrl.toString(), { method: 'PATCH', headers: { Authorization: `Bearer ${tok}` } });
    }
  } catch {}

  // Redirect back to original target stored before login
  const redirectTo = consumeRedirectCookie(cookies) ?? url.searchParams.get('redirect_uri') ?? '/';
  return new Response(null, { status: 302, headers: { Location: redirectTo } });
};


