import { NextRequest, 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";

// Admin user IDs (Rocky)
const ADMIN_IDS = [
  // Add Rocky's user ID here when known
];

/**
 * GET /api/admin/weekend-summary
 *
 * Returns a summary of weekend activity: hires, payments, issues.
 * Query params: ?from=YYYY-MM-DD&to=YYYY-MM-DD
 */
export async function GET(request: NextRequest) {
  try {
    const supabase = await createClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // For now, allow any authenticated user with contractor role
    // TODO: Restrict to admin users when admin system is built
    const admin = getSupabaseAdmin();

    const { searchParams } = new URL(request.url);

    // Default: last weekend (Saturday 00:00 to Sunday 23:59)
    const now = new Date();
    const dayOfWeek = now.getDay(); // 0=Sun, 6=Sat
    const lastSaturdayOffset = dayOfWeek === 0 ? 1 : dayOfWeek === 6 ? 0 : dayOfWeek + 1;
    const lastSaturday = new Date(now);
    lastSaturday.setDate(now.getDate() - lastSaturdayOffset);
    lastSaturday.setHours(0, 0, 0, 0);

    const lastSunday = new Date(lastSaturday);
    lastSunday.setDate(lastSaturday.getDate() + 1);
    lastSunday.setHours(23, 59, 59, 999);

    const fromStr = searchParams.get("from") || lastSaturday.toISOString();
    const toStr = searchParams.get("to") || lastSunday.toISOString();

    // Weekend hires
    const { data: hires, count: hireCount } = await admin
      .from("matches")
      .select(
        "id, status, hired_at, worker_id, jobs!inner(title, companies!inner(name))",
        { count: "exact" }
      )
      .eq("status", "hired")
      .gte("hired_at", fromStr)
      .lte("hired_at", toStr)
      .order("hired_at", { ascending: false });

    // Weekend payments
    const { data: payments, count: paymentCount } = await admin
      .from("payments")
      .select("id, status, amount, stripe_payment_id, match_id, created_at", {
        count: "exact",
      })
      .gte("created_at", fromStr)
      .lte("created_at", toStr)
      .order("created_at", { ascending: false });

    const chargedPayments = payments?.filter((p) => p.status === "charged") || [];
    const pendingPayments = payments?.filter((p) => p.status === "pending") || [];
    const totalRevenue = chargedPayments.reduce(
      (sum, p) => sum + (p.amount || 50),
      0
    );

    // Weekend issues
    const { data: issues, count: issueCount } = await admin
      .from("issue_reports")
      .select("id, category, status, description, created_at", {
        count: "exact",
      })
      .gte("created_at", fromStr)
      .lte("created_at", toStr)
      .order("created_at", { ascending: false });

    // Weekend signups
    const { count: newSignups } = await admin
      .from("profiles")
      .select("*", { count: "exact", head: true })
      .gte("created_at", fromStr)
      .lte("created_at", toStr);

    return NextResponse.json({
      period: { from: fromStr, to: toStr },
      summary: {
        hires: hireCount || 0,
        payments: {
          total: paymentCount || 0,
          charged: chargedPayments.length,
          pending: pendingPayments.length,
          revenue: totalRevenue,
        },
        issues: {
          total: issueCount || 0,
          open: issues?.filter((i) => i.status === "open").length || 0,
          safety: issues?.filter((i) => i.category === "safety").length || 0,
        },
        newSignups: newSignups || 0,
      },
      hires: hires || [],
      payments: payments || [],
      issues: issues || [],
    });
  } catch (error) {
    logger.error("Weekend summary error:", error);
    return NextResponse.json(
      { error: "Failed to generate summary" },
      { status: HTTP_STATUS_INTERNAL_SERVER_ERROR }
    );
  }
}
