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

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

/**
 * POST /api/admin/media/batch-complete
 * Emits exactly ONE MEDIA_BULK_UPLOADED audit event when a multi-file upload batch completes.
 * Fully idempotent: repeated invocations for the same batchId will not create duplicate audit events.
 */
export async function POST(req: NextRequest) {
  try {
    const auditCtx = await getAdminAuditContext(req);
    const canUpload =
      userHasPermission(auditCtx.user, "media.manage") ||
      userHasPermission(auditCtx.user, "posts.create") ||
      userHasPermission(auditCtx.user, "posts.edit");
    if (!canUpload) {
      return NextResponse.json(
        { error: "Forbidden: Missing required media permission." },
        { status: 403 }
      );
    }

    const body = await req.json();
    const batchId = typeof body.batchId === "string" ? body.batchId.trim() : "";
    const totalCount = typeof body.totalCount === "number" ? body.totalCount : 0;
    const completedCount = typeof body.completedCount === "number" ? body.completedCount : 0;
    const failedCount = typeof body.failedCount === "number" ? body.failedCount : 0;
    const filenames = Array.isArray(body.filenames) ? body.filenames : [];
    const failedNames = Array.isArray(body.failedNames) ? body.failedNames : [];

    if (!batchId || completedCount <= 0) {
      return NextResponse.json({ ok: true, ignored: true });
    }

    // Check idempotency: avoid logging the same batch twice
    const existingLogs = await db.getContentLogs({ limit: 50 });
    const isAlreadyLogged = existingLogs.some(
      (l) => l.action === "MEDIA_BULK_UPLOADED" && (l.details as any)?.batchId === batchId
    );

    if (isAlreadyLogged) {
      return NextResponse.json({ ok: true, deduplicated: true });
    }

    await db.logContentEvent({
      actorId: auditCtx.user.id,
      actorName: auditCtx.user.name,
      actorEmail: auditCtx.user.email,
      actorRole: auditCtx.user.role,
      postId: null,
      postTitle: null,
      postSlug: null,
      action: "MEDIA_BULK_UPLOADED",
      details: {
        batchId,
        count: completedCount,
        totalCount,
        failedCount,
        filenames,
        failedNames,
        note: `${completedCount} media asset${completedCount === 1 ? "" : "s"} uploaded in bulk batch`,
      },
      location: auditCtx.location,
    });

    return NextResponse.json({ ok: true });
  } catch (err: any) {
    console.error("[POST /api/admin/media/batch-complete] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to record batch audit log." },
      { status: 500 }
    );
  }
}
