export const dynamic = 'force-dynamic';
import { prisma } from "@/lib/prisma";
import { NextRequest, NextResponse } from "next/server";
import { getCached, setCached } from "@/lib/memoryCache";

const mediaSelect = {
  id: true,
  title: true,
  thumbnailUrl: true,
  duration: true,
  views: true,
  isPremium: true,
  createdAt: true,
  url: true,
  category: { select: { name: true, slug: true } },
  uploader: { select: { id: true, name: true, image: true } }
};

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const limit = Math.min(60, parseInt(searchParams.get("limit") || "32"));
    const page = Math.max(1, parseInt(searchParams.get("page") || "1"));
    const filter = searchParams.get("filter") || "trending";

    // 1. Cache mémoire haute performance (60s)
    const cacheKey = `foryou:${filter}:${page}:${limit}`;
    const cachedData = getCached<any>(cacheKey);
    if (cachedData && cachedData.videos && cachedData.videos.length > 0) {
      const res = NextResponse.json(cachedData);
      res.headers.set("Cache-Control", "public, s-maxage=60, stale-while-revalidate=120");
      return res;
    }

    // Mixte dynamique : 75% vidéos normales, 25% shorts
    const videoQuota = Math.max(1, Math.round(limit * 0.75));
    const shortQuota = Math.max(1, limit - videoQuota);

    let orderBy: any = { createdAt: "desc" };
    if (filter === "views" || filter === "trending") {
      orderBy = { views: "desc" };
    } else if (filter === "new") {
      orderBy = { createdAt: "desc" };
    } else if (filter === "old") {
      orderBy = { createdAt: "asc" };
    }

    const whereBase: any = {
      isPublished: true,
    };

    if (filter === "top_models") {
      whereBase.uploaderId = { not: null };
    }

    // Récupération simultanée exploitant directement les index composites (idx_media_pub_views & idx_media_pub_created)
    const [longVideosRaw, shortsRaw] = await Promise.all([
      prisma.media.findMany({
        where: {
          ...whereBase,
          type: "VIDEO",
        },
        orderBy,
        skip: (page - 1) * videoQuota,
        take: videoQuota * 2,
        select: mediaSelect
      }).catch(() => []),

      prisma.media.findMany({
        where: {
          ...whereBase,
          type: "SHORT",
        },
        orderBy: filter === "trending" ? { views: "desc" } : { createdAt: "desc" },
        skip: (page - 1) * shortQuota,
        take: shortQuota * 2,
        select: mediaSelect
      }).catch(() => [])
    ]);

    // Filtrage mémoire ultra-rapide des embeds tiers
    const longVideos = (longVideosRaw || []).filter((v: any) => !v.url || !v.url.includes("/embed/pm"));
    const shorts = (shortsRaw || []).filter((v: any) => !v.url || !v.url.includes("/embed/pm"));

    const sanitize = (item: any) => {
      const { url, ...clean } = item;
      return clean;
    };

    // Entrelacement régulier : 3 vidéos normales pour 1 short
    const mixed: any[] = [];
    const addedIds = new Set<string>();
    let vIdx = 0;
    let sIdx = 0;

    while (mixed.length < limit && (vIdx < longVideos.length || sIdx < shorts.length)) {
      // 3 vidéos longues
      for (let k = 0; k < 3 && vIdx < longVideos.length && mixed.length < limit; k++) {
        const item = longVideos[vIdx++];
        if (item && !addedIds.has(item.id)) {
          addedIds.add(item.id);
          mixed.push(sanitize(item));
        }
      }
      // 1 short
      if (sIdx < shorts.length && mixed.length < limit) {
        const item = shorts[sIdx++];
        if (item && !addedIds.has(item.id)) {
          addedIds.add(item.id);
          mixed.push(sanitize(item));
        }
      }
    }

    // Remplissage de secours si une des listes s'épuise
    while (vIdx < longVideos.length && mixed.length < limit) {
      const item = longVideos[vIdx++];
      if (item && !addedIds.has(item.id)) {
        addedIds.add(item.id);
        mixed.push(sanitize(item));
      }
    }
    while (sIdx < shorts.length && mixed.length < limit) {
      const item = shorts[sIdx++];
      if (item && !addedIds.has(item.id)) {
        addedIds.add(item.id);
        mixed.push(sanitize(item));
      }
    }

    const payload = {
      videos: mixed,
      total: 100000,
      page,
      totalPages: Math.ceil(100000 / limit),
      personalized: true,
      userLang: "fr"
    };

    if (mixed.length > 0) {
      setCached(cacheKey, payload, 60000);
    }

    const res = NextResponse.json(payload);
    res.headers.set("Cache-Control", "public, s-maxage=60, stale-while-revalidate=120");
    return res;
  } catch (err: any) {
    console.error("Error in foryou route:", err);
    return NextResponse.json({ videos: [], total: 0, page: 1, totalPages: 1, personalized: false, userLang: "fr" });
  }
}
