import { NextRequest, NextResponse } from "next/server";
import { getLogger } from "@/utils/logger";
import { authOptions } from "../../auth/[...nextauth]/auth-options";
import { getServerSession } from "next-auth";

import db from "@/lib/db";

const logger = getLogger("/api/user/payment")

export async function GET(request: NextRequest) {
    try {
        const session = await getServerSession(authOptions);

        if (!session?.user?.profileId) {
            return NextResponse.json({ mssg: "You are not authorized !" }, { status: 403 });
        }

        const { searchParams } = new URL(request.url);

        const page = parseInt(searchParams.get("page") || "1", 10);
        const limit = parseInt(searchParams.get("limit") || "10", 10);

        console.log(page)
        console.log(limit)

        const paymentsData = await db.payments.findMany({
            where: {
                profile_id: session.user.profileId,
                paymentID: {
                    not: null
                }
            },
            orderBy: {
                id: "desc"
            },
            skip: (page - 1) * limit,
            take: limit,
        })


        const totalPayments = await db.payments.count({
            where: { 
                profile_id: session.user.profileId,
                paymentID: {
                    not: null
                }
             }

        });

        

        return NextResponse.json({
            page,
            limit,
            total: totalPayments,
            totalPages: Math.ceil(totalPayments / limit),
            data: paymentsData
        }, { status: 200 });

    } catch (error: any) {
        logger.error("Error occurred when fetching paginated payments", {
            errorMsg: error?.message,
            errorData: error?.config?.data
        });

        return new NextResponse("Internal server error", { status: 500 });
    }
}
