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

export async function GET(req: Request) {
  try {
    const { searchParams } = new URL(req.url);
    const q = searchParams.get("q");
    const page = parseInt(searchParams.get("page") || "1");
    const limit = parseInt(searchParams.get("limit") || "8");

    if (!q || q.trim().length < 2) {
      return NextResponse.json({ videos: [], categories: [], channels: [], total: 0 });
    }

    const cleanQ = q.trim();
    const cacheKey = `search:${cleanQ.toLowerCase()}:${page}:${limit}`;
    const cached = getCached<any>(cacheKey);
    if (cached) {
      const res = NextResponse.json(cached);
      res.headers.set("Cache-Control", "public, s-maxage=60, stale-while-revalidate=120");
      return res;
    }

    const skip = (page - 1) * limit;

    const [videosRaw, categories, channels] = await Promise.all([
      prisma.media.findMany({
        where: { 
          type: "VIDEO", 
          isPublished: true, 
          title: { contains: cleanQ },
        },
        orderBy: { views: "desc" },
        skip,
        take: limit * 2,
        select: {
          id: true, title: true, thumbnailUrl: true, isPremium: true, duration: true, views: true, url: true,
          category: { select: { name: true, slug: true } }
        }
      }).catch(() => []),
      prisma.category.findMany({
        where: { name: { contains: cleanQ } },
        take: 3,
        select: { id: true, name: true, slug: true }
      }).catch(() => []),
      prisma.user.findMany({
        where: { name: { contains: cleanQ }, role: { in: ["CREATOR", "ADMIN"] } },
        take: 3,
        select: { id: true, name: true, image: true, isVerified: true }
      }).catch(() => [])
    ]);

    const videos = videosRaw
      .filter((v: any) => !v.url || !v.url.includes("/embed/pm"))
      .slice(0, limit)
      .map(({ url, ...v }: any) => v);

    const payload = {
      videos,
      categories,
      channels,
      total: videos.length,
      page,
      totalPages: 1
    };

    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 (error) {
    return NextResponse.json({ videos: [], categories: [], channels: [], total: 0 });
  }
}
