/**
 * GET /api/admin/public-audit/cost-summary
 * Operator visibility into public audit volume and estimated cost.
 * Requires admin session (same auth as other /api/admin/* routes).
 */

import { NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

const COST_PER_AUDIT_USD = 1.5;

export async function GET() {
  const { userId } = await auth();
  if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const since30d = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);

  const [totalLeads, completedAudits, last30dCompleted, last30dGateHits] = await Promise.all([
    prisma.lead.count({ where: { source: "public-audit" } }),
    prisma.audit.count({ where: { source: "public", status: "completed" } }),
    prisma.audit.count({ where: { source: "public", status: "completed", completedAt: { gte: since30d } } }),
    prisma.platformEvent.count({
      where: {
        action: "public_audit.gate_hit",
        timestamp: { gte: since30d },
        metadata: { path: ["hadExistingAudit"], equals: true },
      },
    }),
  ]);

  return NextResponse.json({
    totalLeads,
    totalCompletedAudits: completedAudits,
    last30dCompletedAudits: last30dCompleted,
    last30dGateHits: last30dGateHits,
    estimatedLast30dCost: parseFloat((last30dCompleted * COST_PER_AUDIT_USD).toFixed(2)),
    estimatedSavedLast30d: parseFloat((last30dGateHits * COST_PER_AUDIT_USD).toFixed(2)),
  });
}
