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 rows = await sql`
      SELECT
        d.*,
        (SELECT COUNT(*)::int FROM rides r WHERE r.driver_id = d.id) AS total_rides,
        COALESCE((
          SELECT SUM(r.fare_price)::int FROM rides r
          WHERE r.driver_id = d.id AND r.payment_status = 'paid'
        ), 0) AS revenue
      FROM drivers d
      ORDER BY d.id
    `;

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

type DriverBody = {
  first_name?: string;
  last_name?: string;
  profile_image_url?: string;
  car_image_url?: string;
  car_seats?: number;
  rating?: number;
};

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

  try {
    const body = (await request.json()) as DriverBody;

    if (!body.first_name?.trim() || !body.last_name?.trim()) {
      return withCors(
        Response.json(
          { error: "first_name and last_name are required." },
          { status: 400 },
        ),
      );
    }

    const [driver] = await sql`
      INSERT INTO drivers
        (first_name, last_name, profile_image_url, car_image_url, car_seats, rating)
      VALUES
        (${body.first_name.trim()},
         ${body.last_name.trim()},
         ${body.profile_image_url ?? null},
         ${body.car_image_url ?? null},
         ${body.car_seats ?? 4},
         ${body.rating ?? 4.5})
      RETURNING *
    `;

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