/* eslint-disable no-eval */
const fs = eval('require("fs")') as typeof import("fs");
const path = eval('require("path")') as typeof import("path");

import { NextRequest, NextResponse } from "next/server";

const UPLOAD_DIR = path.join(process.cwd(), "public", "uploads", "banners");
const ALLOWED_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
const MAX_SIZE = 10 * 1024 * 1024; // 10MB

export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData();
    const file = formData.get("file") as File | null;
    const panel = formData.get("panel") as string | null;

    if (!file) {
      return NextResponse.json({ error: "Nenhum arquivo enviado." }, { status: 400 });
    }

    if (!panel) {
      return NextResponse.json({ error: "Painel não especificado." }, { status: 400 });
    }

    if (!ALLOWED_TYPES.includes(file.type)) {
      return NextResponse.json(
        { error: "Formato não suportado. Use PNG, JPG, GIF ou WEBP." },
        { status: 400 }
      );
    }

    if (file.size > MAX_SIZE) {
      return NextResponse.json(
        { error: "Arquivo muito grande. Máximo 10MB." },
        { status: 400 }
      );
    }

    // Gerar nome do arquivo
    const ext = file.name.split(".").pop()?.toLowerCase() || "png";
    const fileName = `${panel}_${Date.now()}.${ext}`;
    const filePath = path.join(UPLOAD_DIR, fileName);

    // Garantir que o diretório existe
    if (!fs.existsSync(UPLOAD_DIR)) {
      fs.mkdirSync(UPLOAD_DIR, { recursive: true });
    }

    // Deletar banner antigo deste painel
    const existing = fs.readdirSync(UPLOAD_DIR).filter((f: string) => f.startsWith(`${panel}_`));
    for (const old of existing) {
      fs.unlinkSync(path.join(UPLOAD_DIR, old));
    }

    // Salvar arquivo
    const buffer = Buffer.from(await file.arrayBuffer());
    fs.writeFileSync(filePath, buffer);

    // Retornar URL pública
    const publicUrl = `/uploads/banners/${fileName}`;

    return NextResponse.json({
      success: true,
      url: publicUrl,
      fileName,
      message: "Arquivo enviado com sucesso!",
    });
  } catch (error) {
    return NextResponse.json(
      { error: `Erro ao fazer upload: ${error instanceof Error ? error.message : String(error)}` },
      { status: 500 }
    );
  }
}
