import { NextRequest, NextResponse } from "next/server"; import { prisma } from "@/lib/prisma"; import { requireAdmin, requireAuth } from "@/lib/session"; export async function GET(req: NextRequest) { const session = await requireAuth(); if (!session) return NextResponse.json({ error: "Non autorisé" }, { status: 401 }); try { const homework = await prisma.homework.findMany({ orderBy: { createdAt: "desc" }, where: session.user.role === "ADMIN" ? {} : { OR: [ { userId: null }, { userId: session.user.id }, ], }, }); return NextResponse.json(homework); } catch { return NextResponse.json({ error: "Erreur" }, { status: 500 }); } } export async function POST(req: NextRequest) { const admin = await requireAdmin(); if (!admin) return NextResponse.json({ error: "Admin requis" }, { status: 403 }); const { title, description, videoUrl, userId } = await req.json(); if (!title || !description) { return NextResponse.json({ error: "Titre et description requis" }, { status: 400 }); } try { const homework = await prisma.homework.create({ data: { title, description, videoUrl: videoUrl || null, userId: userId || null, }, }); return NextResponse.json(homework, { status: 201 }); } catch { return NextResponse.json({ error: "Erreur" }, { status: 500 }); } } export async function DELETE(req: NextRequest) { const admin = await requireAdmin(); if (!admin) return NextResponse.json({ error: "Admin requis" }, { status: 403 }); const { id } = await req.json(); if (!id) return NextResponse.json({ error: "id requis" }, { status: 400 }); try { await prisma.homework.delete({ where: { id } }); return NextResponse.json({ ok: true }); } catch { return NextResponse.json({ error: "Erreur" }, { status: 500 }); } }