import { getLogger } from "@/utils/logger";
import { authOptions } from "../../auth/[...nextauth]/auth-options";
import { getServerSession } from "next-auth";
import { NextResponse } from "next/server";
import db from "@/lib/db";

const logger = getLogger("/api/user/coupons");

export async function GET() {

    try {
        const session = await getServerSession(authOptions)

        if (!session || !session.user) {
            return new NextResponse("Forbidden. Not authorized! ", { status: 401 })
        }

        const user = await db.user.findUnique({
            where: {
                uuid: session.user.uuid
            }
        })

        var coupons = await db.coupon.findMany({
            where: {isActive: true}
        })
        
        coupons.forEach(async (coupon, index)=> {
            console.log(coupon)

            const couponUsageCounts = await db.couponUsage.count({
                where: {
                    AND: {
                        couponId: coupon.id,
                        userId: user?.id
                    }
                }
            })

            if (coupon.perUserLimit){
                if (couponUsageCounts > coupon.perUserLimit ) {
                    coupons.splice(index, 1)
                }
            
            }


        })

        return NextResponse.json({'coupons': coupons})

    } catch (error: any) {

        logger.error(
            "An error occurred with fetching coupons for an users",
            { error: error?.config?.data ?? error?.message ?? "Unknown error" }
        )

        return new NextResponse("Internal server error", { status: 500 })
    }

}
