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

export async function GET(request: Request) {
    try {
        const currentUser = await getCurrentUser();
        if (!currentUser) {
            return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }

        const { searchParams } = new URL(request.url);
        const limit = parseInt(searchParams.get("limit") || "20");
        const page = parseInt(searchParams.get("page") || "1");
        const skip = (page - 1) * limit;
        const unreadOnly = searchParams.get("unread_only") === "true";

        const whereClause: any = { user_id: currentUser.id };
        if (unreadOnly) {
            whereClause.is_read = false;
        }

        const [notifications, total, unreadCount] = await Promise.all([
            prisma.notification.findMany({
                where: whereClause,
                orderBy: { created_at: "desc" },
                take: limit,
                skip: skip
            }),
            prisma.notification.count({ where: { user_id: currentUser.id } }),
            prisma.notification.count({ where: { user_id: currentUser.id, is_read: false } })
        ]);

        return NextResponse.json({
            notifications,
            meta: {
                total,
                unread_count: unreadCount,
                page,
                limit,
                total_pages: Math.ceil(total / limit)
            }
        });
    } catch (error) {
        console.error("Fetch Notifications Error:", error);
        return NextResponse.json({ error: "Failed to fetch notifications" }, { status: 500 });
    }
}
