import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function GET(req: NextRequest) {
  try {
    const session = await auth();
    const role = (session?.user as any)?.role;
    if (!["ADMIN", "SUPERADMIN", "MODERATOR"].includes(role)) {
      return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
    }

    const { searchParams } = new URL(req.url);
    const search = searchParams.get("search") || "";
    const type = searchParams.get("type") || "ALL";
    const premium = searchParams.get("premium") || "ALL";
    const page = Math.max(1, parseInt(searchParams.get("page") || "1"));
    const limit = Math.min(100, Math.max(10, parseInt(searchParams.get("limit") || "25")));
    const skip = (page - 1) * limit;

    const where: any = {};
    if (search.trim()) {
      where.title = { contains: search.trim() };
    }
    if (type !== "ALL") {
      where.type = type;
    }
    if (premium === "PREMIUM") {
      where.isPremium = true;
    } else if (premium === "FREE") {
      where.isPremium = false;
    }

    const [items, total] = await Promise.all([
      prisma.media.findMany({
        where,
        orderBy: { createdAt: "desc" },
        skip,
        take: limit,
        select: {
          id: true,
          title: true,
          thumbnailUrl: true,
          type: true,
          
          isPremium: true,
          isPublished: true,
          views: true,
          duration: true,
          createdAt: true,
          uploader: {
            select: { id: true, name: true, email: true }
          }
        }
      }),
      prisma.media.count({ where })
    ]);

    return NextResponse.json({
      media: items,
      pagination: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit)
      }
    });
  } catch (error: any) {
    console.error("Error in GET /api/admin/media:", error);
    return NextResponse.json({ error: error.message || "Erreur serveur" }, { status: 500 });
  }
}
