import { NextResponse } from "next/server";
import { verifyAdminAuth } from "@/lib/adminAuth";
import { writeFile, mkdir } from "fs/promises";
import path from "path";
import { v4 as uuidv4 } from "uuid";

export const dynamic = "force-dynamic";

export async function POST(req: Request) {
  try {
    const isAuthorized = await verifyAdminAuth(req);
    if (!isAuthorized) {
      return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
    }

    const formData = await req.formData();
    const file = formData.get("file") as File | null;

    if (!file || file.size === 0) {
      return NextResponse.json({ error: "Aucun fichier reçu" }, { status: 400 });
    }

    const bytes = await file.arrayBuffer();
    const buffer = Buffer.from(bytes);

    let ext = (file.name.split(".").pop() || "jpg").toLowerCase();
    const allowed = ["jpg", "jpeg", "png", "webp", "gif", "svg"];
    if (!allowed.includes(ext)) {
      ext = "jpg";
    }

    const uploadsDir = path.join(process.cwd(), "public", "uploads", "ads");
    await mkdir(uploadsDir, { recursive: true }).catch(() => {});

    const filename = `ad_${Date.now()}_${uuidv4().slice(0, 8)}.${ext}`;
    const filepath = path.join(uploadsDir, filename);

    await writeFile(filepath, buffer);

    const publicUrl = `/uploads/ads/${filename}`;
    return NextResponse.json({ success: true, url: publicUrl });
  } catch (error: any) {
    console.error("Upload ad banner error:", error);
    return NextResponse.json({ error: error.message || "Erreur lors de l'upload" }, { status: 500 });
  }
}
