/**
 * GET /api/client-portal/audit-log?portalId=X&limit=50
 * Returns recent client portal actions for agency review.
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const { searchParams } = new URL(req.url);
  const portalId = searchParams.get("portalId");
  if (!portalId) return NextResponse.json({ error: "portalId required" }, { status: 400 });

  const portal = await prisma.clientPortal.findUnique({
    where: { id: portalId },
    include: { brand: { include: { organization: { include: { memberships: true } } } } },
  });
  if (!portal) return NextResponse.json({ error: "Portal not found" }, { status: 404 });
  if (!portal.brand.organization.memberships.some((m) => m.userId === user.id)) return NextResponse.json({ error: "Access denied" }, { status: 403 });

  const limit = Math.max(1, Math.min(200, Number(searchParams.get("limit") || 50)));
  const logs = await prisma.portalAuditLog.findMany({ where: { portalId }, orderBy: { timestamp: "desc" }, take: limit });
  return NextResponse.json({ logs });
}
