import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

const MONITOR_TOKEN = process.env.TRAFFIC_MONITOR_TOKEN;

export async function GET(request: NextRequest) {
  if (MONITOR_TOKEN) {
    const token = request.headers.get("x-traffic-token");
    if (token !== MONITOR_TOKEN) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
  }

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

  const [summaryRows, totalRows] = await Promise.all([
    prisma.auditEvent.groupBy({
      by: ["action"],
      where: {
        createdAt: { gte: since },
      },
      _count: { _all: true },
    }),
    prisma.auditEvent.count({
      where: { createdAt: { gte: since } },
    }),
  ]);

  const actionSummary = Object.fromEntries(
    summaryRows.map((row) => [row.action, row._count._all])
  );

  return NextResponse.json({
    period_hours: 24,
    total_events: totalRows,
    action_summary: actionSummary,
    updated_at: new Date().toISOString(),
  });
}
