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

export const dynamic = "force-dynamic";

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;

  try {
    const media = await prisma.media.findUnique({
      where: { id, isPublished: true },
      select: { url: true },
    });

    if (!media?.url) {
      return NextResponse.json({ error: "Media not found" }, { status: 404 });
    }

    const embedUrl = media.url;
    
    if (!embedUrl.includes("pornhub.com/embed")) {
      // Si ce n'est pas Pornhub (ex: mp4 de test local), on renvoie l'URL brute
      return NextResponse.json({ videoUrl: embedUrl });
    }

    const headers = {
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
      "Referer": "https://www.pornhub.com/",
    };

    const res = await fetch(embedUrl, { headers });
    if (!res.ok) {
      return NextResponse.json({ error: "Failed to fetch Pornhub embed" }, { status: 500 });
    }

    const html = await res.text();

    // Recherche en priorité de l'objet contenant "format":"mp4" et sa "videoUrl"
    // Format type: {"group":1,"height":720,"width":1280,...,"format":"mp4","videoUrl":"https:\/\/www.pornhub.com\/video\/get_media?s=..."}
    const mp4Matches = html.matchAll(/{[^{}]*?"format"\s*:\s*"mp4"[^{}]*?}/g);
    let bestMp4Url = "";
    let maxHeight = 0;

    for (const m of mp4Matches) {
      try {
        // Nettoyage sommaire de l'objet JS pour le parser en JSON
        const objText = m[0].replace(/\\/g, "");
        // Extraction par regex simple de la videoUrl et de la hauteur pour prendre la meilleure qualité
        const urlMatch = objText.match(/"videoUrl"\s*:\s*"(.*?)"/);
        const heightMatch = objText.match(/"height"\s*:\s*(\d+)/);
        
        if (urlMatch && urlMatch[1]) {
          const height = heightMatch ? parseInt(heightMatch[1]) : 480;
          // On évite la 4K si possible (trop lourd pour des Shorts), on préfère 720p ou 1080p, ou le premier trouvé
          if (height > maxHeight && height <= 1080) {
            maxHeight = height;
            bestMp4Url = urlMatch[1];
          } else if (!bestMp4Url) {
            bestMp4Url = urlMatch[1];
          }
        }
      } catch {}
    }

    if (bestMp4Url) {
      return NextResponse.json({ videoUrl: bestMp4Url });
    }

    // Fallback: recherche de toute videoUrl mp4 par regex simple dans flashvars
    const fallbackMatch = html.match(/"videoUrl"\s*:\s*"(https:\/\/www\.pornhub\.com\/video\/get_media.*?)"/);
    if (fallbackMatch) {
      return NextResponse.json({ videoUrl: fallbackMatch[1].replace(/\\/g, "") });
    }

    // Fallback HLS (master.m3u8) si pas de mp4 direct trouvé
    const mediaDefsMatch = html.match(/"mediaDefinitions"\s*:\s*(\[.*?\])/);
    if (mediaDefsMatch) {
      try {
        const defs = JSON.parse(mediaDefsMatch[1].replace(/\\/g, ""));
        const hlsDef = defs.find((d: any) => d.format === "hls" || d.videoUrl?.includes(".m3u8"));
        if (hlsDef?.videoUrl) {
          return NextResponse.json({ videoUrl: hlsDef.videoUrl });
        }
      } catch {}
    }

    return NextResponse.json({ error: "No direct video URL found" }, { status: 404 });
  } catch (err: any) {
    return NextResponse.json({ error: err.message || "Internal server error" }, { status: 500 });
  }
}
