import type { RequestHandler } from '@sveltejs/kit';
import { buildAuthorizeUrl, createOAuthState, setStateCookie, setRedirectCookie, setBeatLeaderSessionFromSetCookieHeaders } from '$lib/server/beatleaderAuth';

export const GET: RequestHandler = async ({ url, cookies }) => {
  const origin = url.origin;
  const state = createOAuthState();
  setStateCookie(cookies, state);
  // Persist desired post-login redirect for callback
  const redirectTo = url.searchParams.get('redirect_uri');
  setRedirectCookie(cookies, redirectTo ?? '/');
  // Align with BeatLeader's documented scope naming (prefixed with scp:)
  const scopes = ['scp:profile', 'scp:offline_access'];
  const authUrl = buildAuthorizeUrl(origin, scopes);
  // Always show consent to avoid silent failures and make the grant explicit
  authUrl.searchParams.set('prompt', 'consent');
  authUrl.searchParams.set('state', state);
  // If user already has a BeatLeader website session in the current browser, prime our session by hitting a lightweight endpoint.
  try {
    const probe = await fetch('https://api.beatleader.com/user', { credentials: 'include' as RequestCredentials });
    // If the probe set any cookies, capture them for future session-based calls
    const setCookieHeaders = (probe.headers as any).getSetCookie?.() ?? probe.headers.get('set-cookie')?.split(',') ?? [];
    setBeatLeaderSessionFromSetCookieHeaders(cookies, Array.isArray(setCookieHeaders) ? setCookieHeaders : [setCookieHeaders]);
  } catch {}
  return new Response(null, { status: 302, headers: { Location: authUrl.toString() } });
};


