import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { requireAdmin } from "@/lib/admin-guard";
import { generateAltForMedia } from "@/lib/seo/image-alt";

/**
 * POST /api/admin/media/bulk-generate-alt
 * body: { limit?: number, onlyMissing?: boolean }
 *
 * Iterate media that are missing alt (or explicitly limit), generate suggestions
 * and persist directly. Returns the count + per-item summary.
 */
export const runtime = "nodejs";
export const dynamic = "force-dynamic";

export async function POST(req: Request) {
  const user = await requireAdmin();
  let body: { limit?: number; onlyMissing?: boolean };
  try {
    body = (await req.json()) as { limit?: number; onlyMissing?: boolean };
  } catch {
    body = {};
  }
  const limit = Math.min(50, Math.max(1, body.limit ?? 20));
  const onlyMissing = body.onlyMissing !== false;

  const where = onlyMissing
    ? { OR: [{ alt: null }, { alt: "" }] }
    : {};

  const medias = await prisma.media.findMany({
    where,
    take: limit,
    orderBy: { createdAt: "desc" },
    select: { id: true, url: true, filename: true, alt: true },
  });

  const results: Array<{
    id: string;
    filename: string;
    alt: string;
    source: string;
  }> = [];

  for (const m of medias) {
    const sug = await generateAltForMedia(m);
    if (!sug.alt) continue;
    await prisma.media.update({ where: { id: m.id }, data: { alt: sug.alt, altSource: sug.source } });
    results.push({
      id: m.id,
      filename: m.filename,
      alt: sug.alt,
      source: sug.source,
    });
  }

  await prisma.auditLog.create({
    data: {
      actorId: user.id,
      actorName: user.name,
      actorEmail: user.email,
      source: "admin",
      action: "media.bulk_alt_generate",
      target: "",
      meta: { count: results.length, limit, onlyMissing } as never,
    },
  });

  return NextResponse.json({
    ok: true,
    processed: medias.length,
    updated: results.length,
    results,
  });
}
