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

/**
 * POST /auth/beatleader/steam-ticket
 * Body: { ticket: string } or form-data ticket=...
 *
 * Mirrors BeatLeader mod auth flow by forwarding the Steam session ticket
 * to BeatLeader /signin with provider=steamTicket, capturing BL website cookies.
 */
export const POST: RequestHandler = async ({ request, cookies, fetch }) => {
  try {
    const contentType = request.headers.get('content-type') || '';
    let ticket = '';
    if (contentType.includes('application/json')) {
      const body = await request.json();
      ticket = String((body as any)?.ticket ?? '').trim();
    } else {
      const form = await request.formData();
      ticket = String(form.get('ticket') ?? '').trim();
    }

    if (!ticket) {
      return new Response(JSON.stringify({ error: 'Missing ticket' }), {
        status: 400,
        headers: { 'content-type': 'application/json' }
      });
    }

    const form = new FormData();
    form.set('ticket', ticket);
    form.set('provider', 'steamTicket');
    form.set('returnUrl', '/');

    const res = await fetch('https://api.beatleader.com/signin', {
      method: 'POST',
      body: form,
      redirect: 'manual'
    });

    // Capture BL session cookies regardless of status
    try {
      const setCookieHeaders = (res.headers as any).getSetCookie?.() ?? res.headers.get('set-cookie')?.split(',') ?? [];
      setBeatLeaderSessionFromSetCookieHeaders(cookies, Array.isArray(setCookieHeaders) ? setCookieHeaders : [setCookieHeaders]);
    } catch {}

    const ok = res.status >= 200 && res.status < 400;
    if (!ok) {
      const text = await res.text().catch(() => '');
      return new Response(JSON.stringify({ error: `BeatLeader signin failed (${res.status})`, details: text }), {
        status: 400,
        headers: { 'content-type': 'application/json' }
      });
    }

    return new Response(JSON.stringify({ ok: true }), { headers: { 'content-type': 'application/json' } });
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Unknown error';
    return new Response(JSON.stringify({ error: message }), {
      status: 500,
      headers: { 'content-type': 'application/json' }
    });
  }
};


