import { NextRequest, NextResponse } from "next/server";
import prisma from "@/lib/db";
import { getSession } from "@/lib/auth";

export async function GET(_: NextRequest, { params }: { params: Promise<{ id: string }> }) {
    const { id } = await params;
    try {
        const project = await prisma.project.findUnique({ where: { id }, include: { category: true } });
        if (!project) return NextResponse.json({ error: "Non trouvé" }, { status: 404 });
        return NextResponse.json(project);
    } catch { return NextResponse.json({ error: "Erreur serveur" }, { status: 500 }); }
}

export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
    const session = await getSession();
    if (!session) return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
    const { id } = await params;
    try {
        const data = await req.json();

        // Sanitize data to only include valid project fields
        const { title, description, categoryId, status, featured, image, videoUrl, repoUrl, liveUrl, technologies } = data;

        const project = await prisma.project.update({
            where: { id },
            data: {
                title,
                description,
                categoryId,
                status,
                featured,
                image,
                videoUrl,
                repoUrl,
                liveUrl,
                technologies: Array.isArray(technologies) ? technologies : undefined
            }
        });
        return NextResponse.json(project);
    } catch (e: any) {
        console.error("PUT Project Error:", e);
        return NextResponse.json({ error: e.message || "Erreur serveur" }, { status: 500 });
    }
}

export async function DELETE(_: NextRequest, { params }: { params: Promise<{ id: string }> }) {
    const session = await getSession();
    if (!session) return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
    const { id } = await params;
    try {
        await prisma.project.delete({ where: { id } });
        return NextResponse.json({ success: true });
    } catch { return NextResponse.json({ error: "Erreur serveur" }, { status: 500 }); }
}
