import { NextRequest, NextResponse } from "next/server";
import prisma from "@/lib/db";
import { getSession } from "@/lib/auth";
import { unlink } from "fs/promises";
import { join } from "path";

export async function GET() {
    const session = await getSession();
    if (!session) return NextResponse.json({ error: "Non autorisé" }, { status: 401 });

    try {
        const media = await prisma.media.findMany({ orderBy: { createdAt: "desc" } });
        return NextResponse.json(media);
    } catch { return NextResponse.json({ error: "Erreur serveur" }, { status: 500 }); }
}

export async function DELETE(req: NextRequest) {
    const session = await getSession();
    if (!session) return NextResponse.json({ error: "Non autorisé" }, { status: 401 });

    try {
        const { searchParams } = new URL(req.url);
        const id = searchParams.get("id");
        if (!id) return NextResponse.json({ error: "ID requis" }, { status: 400 });

        const media = await prisma.media.findUnique({ where: { id } });
        if (!media) return NextResponse.json({ error: "Média non trouvé" }, { status: 404 });

        // Delete from file system if it's a local file
        if (media.url.startsWith("/uploads/")) {
            try {
                const filePath = join(process.cwd(), "public", media.url);
                await unlink(filePath);
            } catch (err) {
                console.error("Could not delete physical file:", err);
            }
        }

        await prisma.media.delete({ where: { id } });
        return NextResponse.json({ success: true });
    } catch { return NextResponse.json({ error: "Erreur lors de la suppression" }, { status: 500 }); }
}
