export const dynamic = 'force-dynamic';
export const maxDuration = 300;
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { auth } from "@/lib/auth";
import { writeFile, mkdir } from "fs/promises";
import path from "path";
import crypto from "crypto";
import { v4 as uuidv4 } from "uuid";

export async function POST(req: Request) {
  try {
    const formData = await req.formData();
    const file = formData.get("file") as File | null;
    const type = formData.get("type") as string | null;

    // Support direct image upload for admin banners, hero cards, ads
    const isImage = type === "image" || (file && file.name && /\.(jpg|jpeg|png|webp|gif|svg)$/i.test(file.name));
    if (isImage && file && file.size > 0) {
      const bytes = await file.arrayBuffer();
      const buffer = Buffer.from(bytes);
      const uploadsDir = path.join(process.cwd(), "public", "uploads", "ads");
      await mkdir(uploadsDir, { recursive: true }).catch(() => {});
      const ext = (file.name.split(".").pop() || "jpg").toLowerCase();
      const filename = `hero_${Date.now()}_${uuidv4().slice(0, 8)}.${ext}`;
      await writeFile(path.join(uploadsDir, filename), buffer);
      return NextResponse.json({ success: true, url: `/uploads/ads/${filename}` });
    }

    let finalUploaderId: string | null = null;
    try {
      const session = await auth().catch(() => null);
      if (session?.user?.id) {
        finalUploaderId = session.user.id;
      }
    } catch (_) {}

    if (!finalUploaderId) {
      let defaultUser = await prisma.user.findFirst({
        where: { name: "Utilisateur" },
        select: { id: true }
      }).catch(() => null);

      if (!defaultUser) {
        defaultUser = await prisma.user.findFirst({ select: { id: true } }).catch(() => null);
      }
      finalUploaderId = defaultUser?.id || null;
    }

    // Récupérer l'adresse IP
    const forwardedFor = req.headers.get("x-forwarded-for");
    const realIp = req.headers.get("x-real-ip");
    const uploaderIp = forwardedFor ? forwardedFor.split(",")[0].trim() : (realIp || "127.0.0.1");

    const title = (formData.get("title") as string) || "";
    const description = (formData.get("description") as string) || "";
    const categoryIdParam = (formData.get("categoryId") as string) || "";
    const durationParam = (formData.get("duration") as string) || "15";
    const tagsParam = (formData.get("tags") as string) || "";
    const format = ((formData.get("format") as string) || "LONG").toUpperCase(); // "SHORT" ou "LONG"
    const videoFile = file;

    if (!title || title.trim().length < 1) {
      return NextResponse.json({ error: "Le titre de la vidéo est requis." }, { status: 400 });
    }

    // Valider la catégorie pour éviter les erreurs de clé étrangère
    let finalCategoryId: string | null = null;
    if (categoryIdParam && categoryIdParam.trim().length > 0) {
      const catExists = await prisma.category.findUnique({
        where: { id: categoryIdParam.trim() },
        select: { id: true }
      }).catch(() => null);
      finalCategoryId = catExists?.id || null;
    }

    if (!finalCategoryId && format === "SHORT") {
      const shortsCat = await prisma.category.findFirst({
        where: { slug: "shorts" },
        select: { id: true }
      }).catch(() => null);
      finalCategoryId = shortsCat?.id || null;
    }

    let url = (formData.get("url") as string) || "";
    let fileHash: string | null = null;

    // Traitement du fichier vidéo
    if (videoFile && videoFile.size > 0) {
      const bytes = await videoFile.arrayBuffer();
      const buffer = Buffer.from(bytes);

      fileHash = crypto.createHash("sha256").update(buffer).digest("hex");

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

      let extension = (videoFile.name.split('.').pop() || "mp4").toLowerCase();
      const allowedExtensions = ["mp4", "webm", "mkv", "mov", "avi", "m4v"];
      if (!allowedExtensions.includes(extension)) {
        extension = "mp4";
      }
      const filename = `${uuidv4()}.${extension}`;
      const filepath = path.join(uploadsDir, filename);

      await writeFile(filepath, buffer);
      url = `/uploads/videos/${filename}`;
    }

    if (!url) {
      return NextResponse.json({ error: "Veuillez sélectionner un fichier vidéo valide." }, { status: 400 });
    }

    let thumbnailUrl: string | null = (formData.get("thumbnailUrl") as string) || null;
    const thumbnailFile = formData.get("thumbnailFile") as File | null;
    const capturedThumbData = formData.get("capturedThumbData") as string | null;

    if (thumbnailFile && thumbnailFile.size > 0) {
      const bytes = await thumbnailFile.arrayBuffer();
      const buffer = Buffer.from(bytes);
      const thumbsDir = path.join(process.cwd(), "public", "uploads", "thumbnails");
      await mkdir(thumbsDir, { recursive: true }).catch(() => {});
      let ext = (thumbnailFile.name.split('.').pop() || "jpg").toLowerCase();
      const filename = `${uuidv4()}.${ext}`;
      const filepath = path.join(thumbsDir, filename);
      await writeFile(filepath, buffer);
      thumbnailUrl = `/uploads/thumbnails/${filename}`;
    } else if (capturedThumbData && capturedThumbData.startsWith("data:image")) {
      const base64Data = capturedThumbData.replace(/^data:image\/\w+;base64,/, "");
      const buffer = Buffer.from(base64Data, 'base64');
      const thumbsDir = path.join(process.cwd(), "public", "uploads", "thumbnails");
      await mkdir(thumbsDir, { recursive: true }).catch(() => {});
      const filename = `${uuidv4()}.jpg`;
      const filepath = path.join(thumbsDir, filename);
      await writeFile(filepath, buffer);
      thumbnailUrl = `/uploads/thumbnails/${filename}`;
    }

    const mediaId = uuidv4();
    const now = new Date();
    const finalDuration = parseInt(durationParam) || 15;
    const finalTags = tagsParam ? tagsParam.trim() : (format === "SHORT" ? "#shorts" : "");

    // 1. Insertion sécurisée via Prisma
    let createdMedia: any = null;
    try {
      createdMedia = await prisma.media.create({
        data: {
          id: mediaId,
          title: title.trim(),
          description: description ? description.trim() : "",
          type: "VIDEO",
          format: format === "SHORT" ? "SHORT" : "LONG",
          url,
          thumbnailUrl: thumbnailUrl || null,
          fileHash,
          uploaderIp,
          status: "ACTIVE",
          categoryId: finalCategoryId,
          duration: finalDuration,
          tags: finalTags,
          isPremium: false,
          isPublished: true,
          uploaderId: finalUploaderId,
        }
      });
    } catch (prismaErr: any) {
      console.warn("Prisma create fallback to direct SQL:", prismaErr.message);

      // 2. Fallback SQL direct si le client Prisma est en retard sur les migrations
      await prisma.$executeRawUnsafe(
        `INSERT INTO "Media" (
          "id", "title", "description", "type", "format", "url", "thumbnailUrl", 
          "fileHash", "uploaderIp", "status", "categoryId", "duration", "tags", 
          "isPremium", "isPublished", "uploaderId", "createdAt", "updatedAt"
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 1, ?, ?, ?)`,
        mediaId,
        title.trim(),
        description ? description.trim() : "",
        "VIDEO",
        format === "SHORT" ? "SHORT" : "LONG",
        url,
        thumbnailUrl || null,
        fileHash,
        uploaderIp,
        "ACTIVE",
        finalCategoryId,
        finalDuration,
        finalTags,
        finalUploaderId,
        now.toISOString(),
        now.toISOString()
      );

      createdMedia = {
        id: mediaId,
        title: title.trim(),
        url,
        format: format === "SHORT" ? "SHORT" : "LONG"
      };
    }

    return NextResponse.json({
      success: true,
      id: createdMedia.id,
      media: createdMedia
    }, { status: 201 });

  } catch (error: any) {
    console.error("Upload route fatal error:", error);
    return NextResponse.json({ 
      error: error.message || "Une erreur est survenue lors de l'enregistrement de la vidéo" 
    }, { status: 500 });
  }
}
