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

export const GET: RequestHandler = async () => {
  const creds = readOAuthCredentials();
  if (!creds) return new Response('{}', { headers: { 'content-type': 'application/json' } });
  return new Response(JSON.stringify({ client_id: creds.client_id, client_secret: creds.client_secret }), {
    headers: { 'content-type': 'application/json' }
  });
};

export const POST: RequestHandler = async ({ request }) => {
  try {
    const contentType = request.headers.get('content-type') || '';
    if (contentType.includes('application/json')) {
      const body = (await request.json()) as any;
      const client_id = String(body.client_id || '').trim();
      const client_secret = String(body.client_secret || '').trim();
      if (!client_id || !client_secret) {
        return new Response('client_id and client_secret are required', { status: 400 });
      }
      storeOAuthCredentials({ client_id, client_secret });
      return new Response(JSON.stringify({ ok: true }), { headers: { 'content-type': 'application/json' } });
    }

    const form = await request.formData();
    const client_id = String(form.get('client_id') || '').trim();
    const client_secret = String(form.get('client_secret') || '').trim();
    if (!client_id || !client_secret) {
      return new Response('client_id and client_secret are required', { status: 400 });
    }
    storeOAuthCredentials({ client_id, client_secret });
    return new Response(JSON.stringify({ ok: true }), { headers: { 'content-type': 'application/json' } });
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Failed to save credentials';
    return new Response(message, { status: 500 });
  }
};


