import type { RequestHandler } from '@sveltejs/kit';
import { getBeatLeaderSessionCookieHeader, getValidAccessToken } from '$lib/server/beatleaderAuth';

const BL_PROFILE_URL = 'https://api.beatleader.com/user/profile';

export const PATCH: RequestHandler = async ({ url, cookies, fetch }) => {
  const token = await getValidAccessToken(cookies);
  const cookieHeader = token ? null : getBeatLeaderSessionCookieHeader(cookies);
  if (!token && !cookieHeader) {
    const redirect = url.searchParams.get('redirect_uri') ?? '/';
    return new Response(
      JSON.stringify({ error: 'Unauthorized', login: '/auth/beatleader/login?redirect_uri=' + encodeURIComponent(redirect) }),
      { status: 401, headers: { 'content-type': 'application/json' } }
    );
  }

  const qs = url.searchParams.toString();
  const endpoint = qs ? `${BL_PROFILE_URL}?${qs}` : BL_PROFILE_URL;

  try {
    const upstreamHeaders: Record<string, string> = token ? { Authorization: `Bearer ${token}` } : cookieHeader ? { Cookie: cookieHeader } : {};
    const res = await fetch(endpoint, { method: 'PATCH', headers: upstreamHeaders });
    const text = await res.text();
    const responseHeaders: Record<string, string> = {
      'content-type': res.headers.get('content-type') || 'text/plain'
    };
    const retryAfter = res.headers.get('Retry-After');
    if (res.status === 429 && retryAfter) responseHeaders['Retry-After'] = retryAfter;
    return new Response(text, { status: res.status, headers: responseHeaders });
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Upstream request failed';
    return new Response(JSON.stringify({ error: message }), { status: 502, headers: { 'content-type': 'application/json' } });
  }
};


