import type { APIRoute } from 'astro';
import { supabase, supabaseEnabled } from '../../../lib/supabase.js';
import { getOrCreateProfile, updateProfile, getUserSubmissions, getProfile } from '../../../lib/auth-queries.js';

export const prerender = false;

const json = (data: any, status = 200) =>
  new Response(JSON.stringify(data), {
    status,
    headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache' },
  });

async function getAuthUser(request: Request) {
  if (!supabaseEnabled || !supabase) {
    return { user: null, error: 'Supabase not configured' };
  }

  const token = request.headers.get('Authorization')?.replace('Bearer ', '');
  if (!token) {
    return { user: null, error: 'No token provided' };
  }

  const { data: { user }, error } = await supabase!.auth.getUser(token);
  if (error || !user) {
    return { user: null, error: error?.message || 'Invalid token' };
  }

  return { user, error: null };
}

export const GET: APIRoute = async ({ params, request }) => {
  const route = params.route || '';

  try {
    if (route === 'profile') {
      const { user, error } = await getAuthUser(request);
      if (!user) return json({ error: error || 'Unauthorized' }, 401);

      const profile = await getOrCreateProfile(user.id, user.email!);
      const submissions = await getUserSubmissions(user.id);

      return json({ profile, submissions });
    }

    return json({ error: 'Not found' }, 404);
  } catch (err: any) {
    console.error('[auth GET]', err);
    return json({ error: 'Server error' }, 500);
  }
};

export const POST: APIRoute = async ({ params, request }) => {
  const route = params.route || '';

  try {
    if (route === 'profile') {
      const { user, error } = await getAuthUser(request);
      if (!user) return json({ error: error || 'Unauthorized' }, 401);

      // Ensure profile exists
      await getOrCreateProfile(user.id, user.email!);

      // If body has update data, apply it
      let body: any = {};
      try {
        body = await request.json();
      } catch {
        // Empty body is fine — just ensure profile exists
      }

      const hasUpdates = body.name || body.city || body.bio || body.github_url || body.website_url;

      if (hasUpdates) {
        // Validate URLs if provided
        if (body.github_url && !isValidUrl(body.github_url)) {
          return json({ error: 'URL GitHub invalid' }, 400);
        }
        if (body.website_url && !isValidUrl(body.website_url)) {
          return json({ error: 'URL website invalid' }, 400);
        }

        // Sanitize text fields
        const updateData = {
          name: sanitize(body.name, 100),
          city: sanitize(body.city, 100),
          bio: sanitize(body.bio, 500),
          github_url: body.github_url?.trim().slice(0, 200) || undefined,
          website_url: body.website_url?.trim().slice(0, 200) || undefined,
        };

        const profile = await updateProfile(user.id, updateData);
        return json({ profile });
      }

      const profile = await getProfile(user.id);
      return json({ profile });
    }

    if (route === 'logout') {
      // Server-side logout — clear any server session if needed
      return new Response(JSON.stringify({ message: 'Logged out' }), {
        status: 200,
        headers: {
          'Content-Type': 'application/json',
          'Cache-Control': 'no-cache',
          'Set-Cookie': [
            'sb-token=; path=/; max-age=0; SameSite=Lax',
            'sb-refresh-token=; path=/; max-age=0; SameSite=Lax',
          ].join(', '),
        },
      });
    }

    return json({ error: 'Not found' }, 404);
  } catch (err: any) {
    console.error('[auth POST]', err);
    return json({ error: 'Server error' }, 500);
  }
};

function isValidUrl(str: string): boolean {
  try {
    const url = new URL(str);
    return url.protocol === 'http:' || url.protocol === 'https:';
  } catch {
    return false;
  }
}

function sanitize(value: string | undefined, maxLen: number): string | undefined {
  if (!value) return undefined;
  return value.trim().slice(0, maxLen).replace(/<[^>]*>/g, '') || undefined;
}
