export const dynamic = 'force-dynamic';
import { prisma } from "@/lib/prisma";
import { NextRequest, NextResponse } from "next/server";
import { expandSearchQuery } from "@/lib/searchTranslation";

export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const mediaId = searchParams.get("mediaId");
  const limit = parseInt(searchParams.get("limit") || "12");

  if (!mediaId) return NextResponse.json({ error: "mediaId requis" }, { status: 400 });

  const currentMedia = await prisma.media.findUnique({
    where: { id: mediaId },
    select: { id: true, title: true, tags: true, categoryId: true, type: true },
  });

  if (!currentMedia) return NextResponse.json([], { status: 200 });

  // 1. Extraire les mots-clés du titre et des tags
  const stopWords = new Set(["le", "la", "les", "de", "des", "du", "un", "une", "et", "en", "a", "à", "dans", "pour", "the", "in", "of", "and", "to", "for", "with", "is", "on", "at", "video", "vidéo", "hd", "4k"]);
  
  const rawWords = [
    ...(currentMedia.title || "").split(/[\s\-_,\.]+/),
    ...(currentMedia.tags || "").split(/[\s,]+/)
  ]
    .map(w => w.toLowerCase().trim())
    .filter(w => w.length > 2 && !stopWords.has(w));

  // Garder seulement 5 mots uniques les plus pertinents
  const uniqueWords = Array.from(new Set(rawWords)).slice(0, 5);
  
  // 2. Élargir avec les traductions (ex: "papa" -> ["dad", "father", "papa"])
  const searchKeywords = expandSearchQuery(uniqueWords.join(" "));

  let videos: any[] = [];
  const excludeIds = [mediaId];

  // 1. Chercher par mots-clés (titre ou tags)
  if (searchKeywords.length > 0) {
    const keywordConditions = searchKeywords.map(k => ({
      title: { contains: k }
    }));
    videos = await prisma.media.findMany({
      where: {
        type: currentMedia.type,
        isPublished: true,
        id: { notIn: excludeIds },
        OR: keywordConditions,
        NOT: { url: { contains: "/embed/pm" } }
      },
      take: limit,
      orderBy: { views: "desc" },
      include: { uploader: true, category: true }
    });
  }

  // 2. D'abord chercher par même catégorie si pas assez
  if (videos.length < limit && currentMedia.categoryId) {
    const fetchedIds = [mediaId, ...videos.map(v => v.id)];
    const catVideos = await prisma.media.findMany({
      where: {
        type: currentMedia.type,
        isPublished: true,
        categoryId: currentMedia.categoryId,
        id: { notIn: fetchedIds },
        NOT: { url: { contains: "/embed/pm" } }
      },
      take: limit - videos.length,
      orderBy: { views: "desc" },
      include: { uploader: true, category: true }
    });
    videos = [...videos, ...catVideos];
  }

  // 3. Si pas assez, compléter avec les vidéos récentes
  if (videos.length < limit) {
    const fetchedIds = [mediaId, ...videos.map(v => v.id)];
    const filler = await prisma.media.findMany({
      where: {
        type: currentMedia.type,
        isPublished: true,
        id: { notIn: fetchedIds },
        NOT: { url: { contains: "/embed/pm" } }
      },
      take: limit - videos.length,
      orderBy: { id: "desc" },
      include: { uploader: true, category: true }
    });
    videos = [...videos, ...filler];
  }

  return NextResponse.json(videos);
}

