import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";

export async function PUT(request: Request, props: { params: Promise<{ id: string }> }) {
    try {
        const currentUser = await getCurrentUser();
        if (!currentUser) {
            return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }

        const { id } = await props.params;
        const notificationId = id;

        // Handle "mark all as read" logic if id is 'all'
        if (notificationId === 'all') {
            await prisma.notification.updateMany({
                where: {
                    user_id: currentUser.id,
                    is_read: false
                },
                data: { is_read: true }
            });
            return NextResponse.json({ message: "All notifications marked as read" });
        }

        // Single notification
        const notification = await prisma.notification.findUnique({
            where: { id: notificationId }
        });

        if (!notification || notification.user_id !== currentUser.id) {
            return NextResponse.json({ error: "Notification not found or unauthorized" }, { status: 404 });
        }

        const updated = await prisma.notification.update({
            where: { id: notificationId },
            data: { is_read: true }
        });

        return NextResponse.json(updated);
    } catch (error) {
        console.error("Update Notification Error:", error);
        return NextResponse.json({ error: "Failed to mark notification as read" }, { status: 500 });
    }
}
