import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { movieCard, seriesCard } from "@/lib/content";
import { gradientFor } from "@/lib/poster";

export const dynamic = "force-dynamic";

export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const q = (searchParams.get("q") ?? "").trim();
  const limit = Math.min(20, Number(searchParams.get("limit") ?? "8"));

  if (!q) {
    const recent = await db.searchLog.findMany({ take: 8, orderBy: { createdAt: "desc" }, select: { query: true } });
    return NextResponse.json({
      query: "",
      suggestion: recent.map((s) => s.query).filter(Boolean),
      movies: [], series: [], actors: [], channels: [], tracks: [],
      total: 0,
    });
  }

  const [movies, series, actors, channels, tracks] = await Promise.all([
    db.movie.findMany({
      where: { status: "published", OR: [{ title: { contains: q } }, { persianTitle: { contains: q } }, { originalTitle: { contains: q } }] },
      include: { genres: true, country: true },
      take: limit,
    }),
    db.series.findMany({
      where: { status: "published", OR: [{ title: { contains: q } }, { persianTitle: { contains: q } }, { originalTitle: { contains: q } }] },
      include: { genres: true, country: true },
      take: limit,
    }),
    db.actor.findMany({
      where: { OR: [{ name: { contains: q } }, { persianName: { contains: q } }] },
      take: limit,
    }),
    db.liveChannel.findMany({
      where: { OR: [{ name: { contains: q } }, { persianName: { contains: q } }] },
      take: limit,
    }),
    db.musicTrack.findMany({
      where: { title: { contains: q } },
      include: { artist: true },
      take: limit,
    }),
  ]);

  db.searchLog.create({ data: { query: q, resultsCount: movies.length + series.length + actors.length + channels.length + tracks.length } }).catch(() => {});

  return NextResponse.json({
    query: q,
    movies: movies.map(movieCard),
    series: series.map(seriesCard),
    actors: actors.map((a) => ({ id: a.id, slug: a.slug, name: a.name, persianName: a.persianName, gradient: gradientFor(a.slug) })),
    channels: channels.map((ch) => ({ id: ch.id, slug: ch.slug, name: ch.name, persianName: ch.persianName, logoColors: gradientFor(ch.slug), status: ch.status, category: ch.categoryId })),
    tracks: tracks.map((t) => ({ id: t.id, slug: t.slug, title: t.title, duration: t.duration, plays: t.plays, coverColors: gradientFor(t.slug), artist: { name: t.artist.name, persianName: t.artist.persianName } })),
    total: movies.length + series.length + actors.length + channels.length + tracks.length,
  });
}
