import { NextRequest, NextResponse } from 'next/server';
import { createServerClient } from '@/shared/db/supabase-client';

// --- ASA GENERATED START ---
// Server-side auth guards for route handlers.
// Security: uses getUser() (verified against Supabase Auth server), NOT getSession() (unverified JWT).
// See: https://supabase.com/docs/reference/javascript/auth-getsession
// --- ASA GENERATED END ---

// --- USER CODE START ---

/**
 * Require authenticated user in a route handler.
 * Uses getUser() for server-side verification — NOT getSession().
 *
 * Usage in route handler:
 * ```ts
 * const { user, response } = await requireAuth(request);
 * if (response) return response;
 * // user is guaranteed to be authenticated
 * ```
 */
export async function requireAuth(request: NextRequest): Promise<{
  user: { id: string; email: string } | null;
  response: NextResponse | null;
}> {
  const supabase = createServerClient();

  // SECURITY: getUser() verifies the JWT against Supabase Auth server.
  // getSession() only reads the JWT from cookies without verification — NOT safe for security checks.
  const { data: { user }, error } = await supabase.auth.getUser();

  if (error || !user) {
    return {
      user: null,
      response: NextResponse.json(
        { error: 'Authentication required' },
        { status: 401 },
      ),
    };
  }

  return {
    user: { id: user.id, email: user.email ?? '' },
    response: null,
  };
}

/**
 * Require specific role in a route handler.
 * Checks profiles.role against required role.
 *
 * Usage:
 * ```ts
 * const { user, response } = await requireRole(request, 'admin');
 * if (response) return response;
 * ```
 */
export async function requireRole(request: NextRequest, role: string): Promise<{
  user: { id: string; email: string; role: string } | null;
  response: NextResponse | null;
}> {
  const { user, response } = await requireAuth(request);
  if (response) return { user: null, response };

  const supabase = createServerClient();
  const { data: profile } = await supabase
    .from('profiles')
    .select('role')
    .eq('id', user!.id)
    .single();

  if (!profile || profile.role !== role) {
    return {
      user: null,
      response: NextResponse.json(
        { error: 'Insufficient permissions' },
        { status: 403 },
      ),
    };
  }

  return {
    user: { ...user!, role: profile.role },
    response: null,
  };
}

// --- USER CODE END ---
