import { NextRequest, NextResponse } from "next/server";
import { db, ContentAction } from "@/lib/admin/db";
import { requirePermission, getAdminAuditContext } from "@/lib/admin/auth";

export const dynamic = "force-dynamic";

export async function GET(req: NextRequest) {
  try {
    // Accessible to Main Admin and any Sub-Admin role possessing content.view_activity
    await requirePermission("content.view_activity", req);

    const { searchParams } = new URL(req.url);
    const action = searchParams.get("action") || undefined;
    const actorId = searchParams.get("actorId") || undefined;
    const postId = searchParams.get("postId") || undefined;
    const limitParam = searchParams.get("limit");
    const limit = limitParam ? parseInt(limitParam, 10) : 100;

    const logs = await db.getContentLogs({
      action,
      actorId,
      postId,
      limit,
    });

    return NextResponse.json({ logs });
  } catch (error) {
    const status = (error as unknown as { status: number }).status || 500;
    return NextResponse.json(
      { error: (error as Error).message || "Access denied." },
      { status }
    );
  }
}

export async function POST(req: NextRequest) {
  try {
    const auditCtx = await getAdminAuditContext(req);

    const body = await req.json();
    const action = body.action as ContentAction;
    const postId = typeof body.postId === "string" ? body.postId : null;
    const postTitle = typeof body.postTitle === "string" ? body.postTitle : null;
    const postSlug = typeof body.postSlug === "string" ? body.postSlug : null;
    const details = (body.details && typeof body.details === "object") ? body.details : {};

    if (!action) {
      return NextResponse.json({ error: "Content action is required." }, { status: 400 });
    }

    const entry = await db.logContentEvent({
      actorId: auditCtx.user.id,
      actorName: auditCtx.user.name,
      actorEmail: auditCtx.user.email,
      actorRole: auditCtx.user.role,
      postId,
      postTitle,
      postSlug,
      action,
      details,
      location: auditCtx.location,
    });

    return NextResponse.json({ ok: true, log: entry });
  } catch (error) {
    const status = (error as unknown as { status: number }).status || 500;
    return NextResponse.json(
      { error: (error as Error).message || "Failed to log content event." },
      { status }
    );
  }
}
