import { NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import { logger } from "@/lib/logger";

/**
 * GET /api/analytics
 * 
 * Returns basic platform stats for the CEO/admin dashboard.
 * Requires authenticated user with contractor profile.
 */
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 });
    }

    // Run all queries in parallel
    const [
      { count: totalWorkers },
      { count: totalContractors },
      { count: totalJobs },
      { count: activeJobs },
      { count: totalMatches },
      { count: hiredMatches },
      { count: totalRatings },
      { data: recentSignups },
    ] = await Promise.all([
      supabase.from("profiles").select("*", { count: "exact", head: true }).eq("type", "worker"),
      supabase.from("profiles").select("*", { count: "exact", head: true }).eq("type", "contractor"),
      supabase.from("jobs").select("*", { count: "exact", head: true }),
      supabase.from("jobs").select("*", { count: "exact", head: true }).eq("status", "active"),
      supabase.from("matches").select("*", { count: "exact", head: true }),
      supabase.from("matches").select("*", { count: "exact", head: true }).eq("status", "hired"),
      supabase.from("ratings").select("*", { count: "exact", head: true }),
      supabase
        .from("profiles")
        .select("type, created_at")
        .gte("created_at", new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString())
        .order("created_at", { ascending: false }),
    ]);

    // Compute signup funnel
    const last7DaysSignups = recentSignups || [];
    const workerSignups7d = last7DaysSignups.filter((p) => p.type === "worker").length;
    const contractorSignups7d = last7DaysSignups.filter((p) => p.type === "contractor").length;

    // Hire rate
    const hireRate = totalMatches && totalMatches > 0
      ? Math.round(((hiredMatches || 0) / totalMatches) * 100)
      : 0;

    return NextResponse.json({
      totals: {
        workers: totalWorkers || 0,
        contractors: totalContractors || 0,
        jobs: totalJobs || 0,
        activeJobs: activeJobs || 0,
        matches: totalMatches || 0,
        hires: hiredMatches || 0,
        ratings: totalRatings || 0,
      },
      funnel: {
        signups7d: {
          workers: workerSignups7d,
          contractors: contractorSignups7d,
          total: last7DaysSignups.length,
        },
        hireRate,
      },
    });
  } catch (error) {
    logger.error("Analytics error:", error);
    return NextResponse.json({ error: "Failed to load analytics" }, { status: 500 });
  }
}
