import { NextRequest, NextResponse } from "next/server";
import { requireAdmin } from "@/lib/api-auth";
import { db, reports, auditLogs, eq } from "@epicure/db";
import { randomUUID } from "crypto";

interface RouteContext {
  params: Promise<{ id: string }>;
}

export async function PATCH(req: NextRequest, { params }: RouteContext) {
  const { session, response } = await requireAdmin({ allowModerator: true });
  if (response) return response;

  const { id } = await params;
  const body = (await req.json()) as { status?: string };
  if (body.status !== "reviewed" && body.status !== "dismissed") {
    return NextResponse.json({ error: "Invalid status" }, { status: 400 });
  }

  const [updated] = await db
    .update(reports)
    .set({ status: body.status, reviewedById: session!.user.id, reviewedAt: new Date() })
    .where(eq(reports.id, id))
    .returning();

  if (!updated) return NextResponse.json({ error: "Not found" }, { status: 404 });

  await db.insert(auditLogs).values({
    id: randomUUID(),
    userId: session!.user.id,
    action: "admin.report.resolve",
    targetType: "report",
    targetId: id,
    metadata: JSON.stringify({ status: body.status }),
    createdAt: new Date(),
  });

  return NextResponse.json({ report: updated });
}
