import { NextResponse } from "next/server";
import { logger } from "@/lib/logger";
import { createClient, getSupabaseAdmin } from "@/lib/supabase/server";
import { HTTP_STATUS_INTERNAL_SERVER_ERROR } from "@/lib/constants";

/**
 * GET /api/admin/launch-metrics
 *
 * Focused launch-day metrics: today / yesterday / 7d comparisons.
 * Designed for 30s auto-refresh during launch.
 */
export async function GET() {
  try {
    const supabase = await createClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const admin = getSupabaseAdmin();
    const now = new Date();

    // Time boundaries (AEDT = UTC+11)
    const todayStart = new Date(now);
    todayStart.setHours(0, 0, 0, 0);

    const yesterdayStart = new Date(todayStart);
    yesterdayStart.setDate(yesterdayStart.getDate() - 1);

    const sevenDaysAgo = new Date(todayStart);
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);

    const todayISO = todayStart.toISOString();
    const yesterdayISO = yesterdayStart.toISOString();
    const sevenDaysISO = sevenDaysAgo.toISOString();

    // All queries in parallel for speed
    const [
      workersToday,
      workersYesterday,
      workers7d,
      workersTotal,
      jobsToday,
      jobsYesterday,
      jobs7d,
      jobsTotal,
      hiresToday,
      hiresYesterday,
      hires7d,
      hiresTotal,
      paymentsCharged7d,
      paymentsTotal7d,
      paymentsFailed7d,
      issuesOpen,
      issuesUrgent,
      recentHires,
      recentWorkers,
    ] = await Promise.all([
      // Workers
      admin.from("worker_profiles").select("id", { count: "exact", head: true }).gte("created_at", todayISO),
      admin.from("worker_profiles").select("id", { count: "exact", head: true }).gte("created_at", yesterdayISO).lt("created_at", todayISO),
      admin.from("worker_profiles").select("id", { count: "exact", head: true }).gte("created_at", sevenDaysISO),
      admin.from("worker_profiles").select("id", { count: "exact", head: true }),

      // Jobs
      admin.from("jobs").select("id", { count: "exact", head: true }).gte("created_at", todayISO),
      admin.from("jobs").select("id", { count: "exact", head: true }).gte("created_at", yesterdayISO).lt("created_at", todayISO),
      admin.from("jobs").select("id", { count: "exact", head: true }).gte("created_at", sevenDaysISO),
      admin.from("jobs").select("id", { count: "exact", head: true }),

      // Hires
      admin.from("matches").select("id", { count: "exact", head: true }).eq("status", "hired").gte("hired_at", todayISO),
      admin.from("matches").select("id", { count: "exact", head: true }).eq("status", "hired").gte("hired_at", yesterdayISO).lt("hired_at", todayISO),
      admin.from("matches").select("id", { count: "exact", head: true }).eq("status", "hired").gte("hired_at", sevenDaysISO),
      admin.from("matches").select("id", { count: "exact", head: true }).eq("status", "hired"),

      // Payments (7d)
      admin.from("payments").select("id, amount", { count: "exact" }).in("status", ["charged", "paid"]).gte("created_at", sevenDaysISO),
      admin.from("payments").select("id", { count: "exact", head: true }).gte("created_at", sevenDaysISO),
      admin.from("payments").select("id", { count: "exact", head: true }).eq("status", "failed").gte("created_at", sevenDaysISO),

      // Issues
      admin.from("issue_reports").select("id", { count: "exact", head: true }).neq("status", "resolved").neq("status", "closed"),
      admin.from("issue_reports").select("id", { count: "exact", head: true }).eq("is_urgent", true).neq("status", "resolved").neq("status", "closed"),

      // Recent hires (last 5)
      admin.from("matches")
        .select("id, hired_at, worker_id, jobs!inner(title, companies!inner(name))")
        .eq("status", "hired")
        .order("hired_at", { ascending: false })
        .limit(5),

      // Recent workers (last 5)
      admin.from("worker_profiles")
        .select("id, created_at, primary_trade, city")
        .order("created_at", { ascending: false })
        .limit(5),
    ]);

    // Payment calculations
    const chargedCount = paymentsCharged7d.count || 0;
    const totalPaymentCount = paymentsTotal7d.count || 0;
    const failedCount = paymentsFailed7d.count || 0;
    const revenue7d = (paymentsCharged7d.data || []).reduce((sum, p) => sum + (p.amount || 0), 0);
    const paymentSuccessRate = totalPaymentCount > 0 ? Math.round((chargedCount / totalPaymentCount) * 100) : 100;
    const errorRate = totalPaymentCount > 0 ? Math.round((failedCount / totalPaymentCount) * 100) : 0;

    const response = {
      timestamp: now.toISOString(),
      workers: {
        today: workersToday.count || 0,
        yesterday: workersYesterday.count || 0,
        sevenDays: workers7d.count || 0,
        total: workersTotal.count || 0,
      },
      jobs: {
        today: jobsToday.count || 0,
        yesterday: jobsYesterday.count || 0,
        sevenDays: jobs7d.count || 0,
        total: jobsTotal.count || 0,
      },
      hires: {
        today: hiresToday.count || 0,
        yesterday: hiresYesterday.count || 0,
        sevenDays: hires7d.count || 0,
        total: hiresTotal.count || 0,
      },
      payments: {
        charged: chargedCount,
        failed: failedCount,
        total: totalPaymentCount,
        revenue7d,
        successRate: paymentSuccessRate,
        errorRate,
      },
      issues: {
        open: issuesOpen.count || 0,
        urgent: issuesUrgent.count || 0,
      },
      recentHires: (recentHires.data || []).map((h) => ({
        id: h.id,
        hiredAt: h.hired_at,
        jobTitle: (h.jobs as unknown as { title: string })?.title,
        company: (h.jobs as unknown as { companies: { name: string } })?.companies?.name,
      })),
      recentWorkers: (recentWorkers.data || []).map((w) => ({
        id: w.id,
        createdAt: w.created_at,
        trade: w.primary_trade || "Unspecified",
        city: w.city || "Unknown",
      })),
    };

    return NextResponse.json(response);
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unknown error";
    logger.error("Launch metrics API error:", message);
    return NextResponse.json(
      { error: "Failed to fetch launch metrics" },
      { status: HTTP_STATUS_INTERNAL_SERVER_ERROR }
    );
  }
}
