import { NextRequest, NextResponse } from "next/server";
import { writeFile, mkdir } from "node:fs/promises";
import path from "path";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";

export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return NextResponse.json({ error: "No autorizado" }, { status: 401 });
    }

    const formData = await req.formData();
    const file = formData.get("file") as File | null;

    if (!file || file.size === 0) {
      return NextResponse.json({ error: "No se envió un archivo." }, { status: 400 });
    }

    // Validar tipo de archivo (MIME)
    const allowedTypes = ["image/png", "image/jpeg", "image/webp", "image/gif"];
    if (!allowedTypes.includes(file.type)) {
      return NextResponse.json({ error: "Tipo de archivo no permitido. Solo imágenes." }, { status: 400 });
    }

    // Validar extensión del archivo
    const allowedExtensions = [".png", ".jpg", ".jpeg", ".webp", ".gif"];
    const ext = path.extname(file.name).toLowerCase();
    
    if (!allowedExtensions.includes(ext)) {
      return NextResponse.json({ error: "Extensión de archivo no permitida." }, { status: 400 });
    }

    // Validar tamaño (max 5MB)
    if (file.size > 5 * 1024 * 1024) {
      return NextResponse.json({ error: "El archivo excede 5MB." }, { status: 400 });
    }

    const bytes = await file.arrayBuffer();
    const buffer = Buffer.from(bytes);

    // Crear carpeta uploads si no existe
    const uploadsDir = path.join(process.cwd(), "public", "uploads");
    await mkdir(uploadsDir, { recursive: true });

    // Nombre único y seguro
    const sanitizedExt = allowedExtensions.includes(ext) ? ext : ".png";
    const filename = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}${sanitizedExt}`;
    const filepath = path.join(uploadsDir, filename);

    // Evitar path traversal
    if (!filepath.startsWith(uploadsDir)) {
      return NextResponse.json({ error: "Ruta de archivo inválida." }, { status: 400 });
    }

    await writeFile(filepath, buffer);

    return NextResponse.json({ url: `/uploads/${filename}` });
  } catch (error) {
    console.error("Upload error:", error);
    return NextResponse.json({ error: "Error al subir el archivo." }, { status: 500 });
  }
}
