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

// Registers a BeatLeader OAuth app using the user's BL session cookie (must be logged in on beatleader.com)
// Validates icon and relays to BeatLeader API, then persists returned client credentials.
export const POST: RequestHandler = async ({ request, fetch, url }) => {
  const form = await request.formData();
  const name = String(form.get('name') ?? '');
  const clientId = String(form.get('clientId') ?? '');
  const scopes = String(form.get('scopes') ?? 'scp:profile');
  const redirectUrls = String(form.get('redirectUrls') ?? '');
  const icon = form.get('icon');

  if (!name || name.length < 2 || name.length > 25) {
    return new Response('Invalid name', { status: 400 });
  }
  if (clientId && clientId.length < 4) {
    return new Response('Client ID must be at least 4 characters long', { status: 400 });
  }
  if (!redirectUrls) {
    return new Response('Redirect URLs required', { status: 400 });
  }

  // Validate icon
  if (icon && icon instanceof File) {
    const valid = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
    if (!valid.includes(icon.type)) return new Response('Icon must be JPG/PNG/GIF', { status: 400 });
    if (icon.size > 5 * 1024 * 1024) return new Response('Icon must be under 5MB', { status: 400 });
  }

  const params = new URLSearchParams({
    name,
    clientId: clientId || generateClientId(),
    scopes,
    redirectUrls
  });
  const endpoint = new URL(`https://api.beatleader.com/developer/app?${params.toString()}`);

  // Forward request including cookies (BeatLeader requires login)
  let blRes: Response;
  if (icon && icon instanceof File) {
    const fd = new FormData();
    fd.set('icon', icon);
    blRes = await fetch(endpoint.toString(), { method: 'POST', body: fd, credentials: 'include' as RequestCredentials });
  } else {
    blRes = await fetch(endpoint.toString(), { method: 'POST', credentials: 'include' as RequestCredentials });
  }

  if (!blRes.ok) {
    const text = await blRes.text();
    const headers: Record<string, string> = {};
    const retryAfter = blRes.headers.get('Retry-After');
    if (blRes.status === 429 && retryAfter) headers['Retry-After'] = retryAfter;
    return new Response(text || 'BeatLeader registration failed', { status: blRes.status, headers });
  }

  const created = (await blRes.json()) as any;
  const out = {
    clientId: created?.clientId ?? created?.client_id,
    clientSecret: created?.clientSecret ?? created?.client_secret,
    name: created?.name,
    scopes: created?.scopes ?? scopes.split(',').map((s) => s.trim()),
    redirectUrls: created?.redirectUrls ?? redirectUrls.split(',').map((s) => s.trim())
  };

  if (!out.clientId || !out.clientSecret) {
    return new Response('BeatLeader response missing credentials', { status: 502 });
  }

  storeOAuthCredentials({ client_id: out.clientId, client_secret: out.clientSecret, scopes: out.scopes, redirect_urls: out.redirectUrls });
  return new Response(JSON.stringify(out), { headers: { 'content-type': 'application/json' } });
};

function generateClientId(): string {
  return 'bl_' + Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
}


