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 [totals] = await sql<{
      users: number;
      drivers: number;
      rides: number;
      revenue: number;
      rides_today: number;
      avg_fare: number;
      pending_count: number;
      pending_revenue: number;
      new_users_7d: number;
    }>`
      SELECT
        (SELECT COUNT(*)::int FROM users) AS users,
        (SELECT COUNT(*)::int FROM drivers) AS drivers,
        (SELECT COUNT(*)::int FROM rides) AS rides,
        (SELECT COALESCE(SUM(fare_price), 0)::int FROM rides WHERE payment_status = 'paid') AS revenue,
        (SELECT COUNT(*)::int FROM rides WHERE created_at >= CURRENT_DATE) AS rides_today,
        (SELECT COALESCE(ROUND(AVG(fare_price)), 0)::int FROM rides WHERE payment_status = 'paid') AS avg_fare,
        (SELECT COUNT(*)::int FROM rides WHERE LOWER(payment_status) <> 'paid') AS pending_count,
        (SELECT COALESCE(SUM(fare_price), 0)::int FROM rides WHERE LOWER(payment_status) <> 'paid') AS pending_revenue,
        (SELECT COUNT(*)::int FROM users WHERE created_at >= CURRENT_DATE - INTERVAL '7 days') AS new_users_7d
    `;

    const trend = await sql<{ day: string; rides: number; revenue: number }>`
      SELECT
        TO_CHAR(DAY, 'YYYY-MM-DD') AS day,
        COUNT(r.ride_id)::int AS rides,
        COALESCE(SUM(r.fare_price) FILTER (WHERE r.payment_status = 'paid'), 0)::int AS revenue
      FROM generate_series(
        CURRENT_DATE - INTERVAL '13 days',
        CURRENT_DATE,
        INTERVAL '1 day'
      ) AS DAY
      LEFT JOIN rides r ON r.created_at >= DAY AND r.created_at < DAY + INTERVAL '1 day'
      GROUP BY DAY
      ORDER BY DAY
    `;

    const topDrivers = await sql<{
      driver_id: number;
      name: string;
      rides: number;
      revenue: number;
    }>`
      SELECT
        d.id AS driver_id,
        d.first_name || ' ' || d.last_name AS name,
        COUNT(r.ride_id)::int AS rides,
        COALESCE(SUM(r.fare_price) FILTER (WHERE r.payment_status = 'paid'), 0)::int AS revenue
      FROM drivers d
      LEFT JOIN rides r ON r.driver_id = d.id
      GROUP BY d.id, d.first_name, d.last_name
      ORDER BY revenue DESC, rides DESC
      LIMIT 5
    `;

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