import { requireOwner, withCors, preflight } from "@/lib/admin";
import { sql } from "@/lib/db";

export async function OPTIONS() {
  return preflight();
}

export async function GET(request: Request) {
  const auth = await requireOwner(request);
  if ("error" in auth) return withCors(auth.error);

  try {
    const url = new URL(request.url);
    const search = url.searchParams.get("q")?.trim().toLowerCase() ?? "";

    const rows = search
      ? await sql<{
          id: string;
          name: string;
          email: string;
          role: string | null;
          email_verified: boolean;
          created_at: string;
          rides: number;
        }>`
        SELECT
          u.id,
          u.name,
          u.email,
          u.role,
          u.email_verified,
          u.created_at,
          (SELECT COUNT(*)::int FROM rides r WHERE r.user_id = u.id) AS rides
        FROM users u
        WHERE (LOWER(u.email) LIKE ${`%${search}%`} OR LOWER(u.name) LIKE ${`%${search}%`})
        ORDER BY u.created_at DESC
        LIMIT 500
      `
      : await sql<{
          id: string;
          name: string;
          email: string;
          role: string | null;
          email_verified: boolean;
          created_at: string;
          rides: number;
        }>`
        SELECT
          u.id,
          u.name,
          u.email,
          u.role,
          u.email_verified,
          u.created_at,
          (SELECT COUNT(*)::int FROM rides r WHERE r.user_id = u.id) AS rides
        FROM users u
        ORDER BY u.created_at DESC
        LIMIT 500
      `;

    return withCors(Response.json({ data: rows }));
  } catch (error) {
    console.error("[ADMIN_USERS]: ", error);
    return withCors(
      Response.json({ error: "Internal Server Error" }, { status: 500 }),
    );
  }
}
