export const dynamic = 'force-dynamic';
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { auth } from "@/lib/auth";

export async function GET(req: Request) {
  try {
    const session = await auth();
    if (!session?.user) return NextResponse.json({ error: "Non autorisé" }, { status: 401 });

    const playlists = await prisma.playlist.findMany({
      where: { userId: session.user.id as string },
      orderBy: { createdAt: "desc" },
      include: {
        _count: { select: { media: true } }
      }
    });

    return NextResponse.json(playlists);
  } catch (error) {
    return NextResponse.json({ error: "Erreur serveur" }, { status: 500 });
  }
}

export async function POST(req: Request) {
  try {
    const session = await auth();
    if (!session?.user) return NextResponse.json({ error: "Non autorisé" }, { status: 401 });

    const { name, mediaId } = await req.json();
    if (!name) return NextResponse.json({ error: "Nom requis" }, { status: 400 });

    const playlist = await prisma.playlist.create({
      data: {
        name,
        userId: session.user.id as string,
        media: mediaId ? { connect: { id: mediaId } } : undefined
      }
    });

    return NextResponse.json(playlist);
  } catch (error) {
    return NextResponse.json({ error: "Erreur serveur" }, { status: 500 });
  }
}

