import { NextRequest, NextResponse } from "next/server";
import { writeFile, mkdir } from "fs/promises";
import path from "path";
import { isOpsAuthed } from "@/lib/ops-auth";

export const runtime = "nodejs";

function safeSlug(input: string) {
  return input
    .toLowerCase()
    .normalize("NFD")
    .replace(/\p{Diacritic}/gu, "")
    .replace(/[^a-z0-9_-]+/g, "-")
    .replace(/^-|-$/g, "")
    .slice(0, 48);
}

export async function POST(req: NextRequest) {
  if (!isOpsAuthed(req)) {
    return NextResponse.json({ message: "No autorizado." }, { status: 401 });
  }

  const form = await req.formData().catch(() => null);
  if (!form) {
    return NextResponse.json({ message: "Formulario inválido." }, { status: 400 });
  }

  const file = form.get("file");
  if (!(file instanceof File)) {
    return NextResponse.json({ message: "Falta el archivo." }, { status: 400 });
  }

  const folder = safeSlug(String(form.get("folder") || "general")) || "general";
  const color = safeSlug(String(form.get("color") || "default")) || "default";
  const ext =
    path.extname(file.name || "").toLowerCase() ||
    (file.type.includes("png")
      ? ".png"
      : file.type.includes("webp")
        ? ".webp"
        : ".jpg");
  const allowed = [".jpg", ".jpeg", ".png", ".webp", ".gif"];
  if (!allowed.includes(ext)) {
    return NextResponse.json(
      { message: "Formato no permitido. Usa JPG, PNG o WEBP." },
      { status: 400 }
    );
  }
  if (file.size > 8 * 1024 * 1024) {
    return NextResponse.json(
      { message: "La imagen no puede superar 8 MB." },
      { status: 400 }
    );
  }

  const dir = path.join(
    process.cwd(),
    "public",
    "products",
    "uploads",
    folder,
    color
  );
  await mkdir(dir, { recursive: true });
  const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}${ext}`;
  const buffer = Buffer.from(await file.arrayBuffer());
  await writeFile(path.join(dir, filename), buffer);

  const url = `/products/uploads/${folder}/${color}/${filename}`;
  const absolute = `https://ot.azulado.cloud${url}`;
  return NextResponse.json({ url, absolute });
}
