import { NextRequest, NextResponse } from "next/server";
import { getAdminAuditContext } from "@/lib/admin/auth";
import { db } from "@/lib/admin/db";
import {
  getMediaReferences,
  deletePhysicalMediaFile,
} from "@/lib/media-storage";
import { deleteAssetFromCloudinary } from "@/lib/cloudinary";

export const dynamic = "force-dynamic";

/**
 * POST /api/admin/media/bulk-delete
 * Safely removes multiple media assets in a single authorized transaction.
 * Enforces reference safety: assets referenced by published content or authors
 * are protected and reported as skipped unless force=true is provided.
 */
export async function POST(req: NextRequest) {
  try {
    const auditCtx = await getAdminAuditContext(req, { permission: "media.manage" });
    const body = await req.json().catch(() => ({}));
    const ids: string[] = Array.isArray(body.ids) ? body.ids : [];
    const force = Boolean(body.force);

    if (ids.length === 0) {
      return NextResponse.json(
        { error: "No media IDs provided for bulk deletion." },
        { status: 400 }
      );
    }

    const deleted: Array<{ id: string; filename: string }> = [];
    const skipped: Array<{ id: string; filename: string; reason: string }> = [];

    for (const id of ids) {
      const item = await db.getMediaById(id);
      if (!item) {
        skipped.push({ id, filename: id, reason: "Asset not found" });
        continue;
      }

      // Check references
      const [refsByUrl, refsById] = await Promise.all([
        getMediaReferences(item.url),
        getMediaReferences(item.id),
      ]);
      const allPosts = Array.from(new Set([...refsByUrl.posts, ...refsById.posts]));
      const allAuthors = Array.from(new Set([...refsByUrl.authors, ...refsById.authors]));
      const totalRefs = allPosts.length + allAuthors.length;

      if (totalRefs > 0 && !force) {
        const reasons: string[] = [];
        if (allPosts.length > 0) reasons.push(`${allPosts.length} article(s)`);
        if (allAuthors.length > 0) reasons.push(`${allAuthors.length} author(s)`);
        skipped.push({
          id: item.id,
          filename: item.filename,
          reason: `Referenced by ${reasons.join(" and ")}`,
        });
        continue;
      }

      // Delete from storage
      try {
        if (item.provider === "cloudinary" && item.publicId) {
          await deleteAssetFromCloudinary(item.publicId);
        } else if (item.url.startsWith("/")) {
          await deletePhysicalMediaFile(item.url);
        }
      } catch (err: any) {
        console.warn(`[bulk-delete] Storage removal error for ${item.id}:`, err.message);
      }

      // Remove from MongoDB
      await db.deleteMedia(item.id);
      deleted.push({ id: item.id, filename: item.filename });
    }

    // Write single authoritative bulk deletion audit event
    if (deleted.length > 0 || skipped.length > 0) {
      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_DELETED",
        details: {
          requestedCount: ids.length,
          deletedCount: deleted.length,
          skippedCount: skipped.length,
          deletedAssets: deleted,
          skippedAssets: skipped,
          forced: force,
        },
        location: auditCtx.location,
      });
    }

    return NextResponse.json({
      success: true,
      deleted,
      skipped,
      totalRequested: ids.length,
    });
  } catch (err: any) {
    console.error("[POST /api/admin/media/bulk-delete] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to execute bulk deletion." },
      { status: err.status || 500 }
    );
  }
}
