import db from "@/lib/db";
import { getServerSession } from "next-auth";
import { authOptions } from "../../auth/[...nextauth]/auth-options";
import { NextResponse } from "next/server";


export async function POST(request: Request) {
    try {
        const session = await getServerSession(authOptions);
        if (!session?.user?.uuid) {
            return NextResponse.json(
                { message: "You are not authorized!" },
                { status: 403 }
            );
        }

        const { code } = await request.json();

        const cart = await db.cart.findUnique({
            where: {
                profile_id: session.user.profileId
            },
            include: {
                CartItem: {
                    include: {
                        variant: {
                            include: {
                                product: {
                                    include: {
                                        category: true,
                                        collection: true,
                                    }
                                }
                            }
                        }
                    }
                }
            }
        })



        if (!code) {
            return NextResponse.json(
                { message: "Coupon code is required" },
                { status: 400 }
            );
        }

        const coupon = await db.coupon.findUnique({
            where: { code },
            include: {
                products: true,
                categories: true,
                collections: true,
                variants: true,
            },
        });

        


        const couponCategoryIds = coupon?.categories.map((c) => c.id);
        const couponProductIds = coupon?.products.map((p) => p.id);
        const couponCollectionIds = coupon?.collections.map((col) => col.id);
        const couponVariantIds = coupon?.variants.map((v) => v.id);




        //console.log(coupon)

        if (!coupon) {
            return NextResponse.json(
                { message: "Invalid coupon code" },
                { status: 404 }
            );
        }

        const now = new Date();

        // Active status
        if (!coupon.isActive) {
            return NextResponse.json(
                { message: "This coupon is not active." },
                { status: 400 }
            );
        }

        // Date validity
        if (coupon.startDate && now < coupon.startDate) {
            return NextResponse.json(
                { message: "This coupon is not yet valid." },
                { status: 400 }
            );
        }

        if (coupon.endDate && now > coupon.endDate) {
            return NextResponse.json(
                { message: "This coupon has expired." },
                { status: 400 }
            );
        }

        // Usage limits
        if (coupon.usageLimit && coupon.usageCount >= coupon.usageLimit) {
            return NextResponse.json(
                { message: "This coupon has reached its max usage limit." },
                { status: 400 }
            );
        }

        //  Per-user usage limit
        const userUsageCount = await db.couponUsage.count({
            where: {
                couponId: coupon.id,
                users: {
                    some: {
                        uuid: session.user.uuid,
                    },
                },
            },
        });

        if (coupon.perUserLimit && userUsageCount >= coupon.perUserLimit) {

            return NextResponse.json(
                { message: "You have already used this coupon for maximum times." },
                { status: 400 }
            );
        }

        // === COUPON IS VALID ===
        // Here, you can filter which products in the user's cart are eligible
        // based on coupon.products, coupon.categories, etc.
        // Example: You can match the cart product IDs to coupon.products IDs on the frontend.

        if (coupon?.minPurchaseAmount && coupon.minPurchaseAmount > (cart?.totalPrice ?? 0)) {
            return NextResponse.json(
                { message: "Cart total does not meet the minimum purchase amount." },
                { status: 400 }
            );
        }

        var applyCoupon = false

        cart?.CartItem.forEach((item) => {
            const variant = item.variant;

            if (couponVariantIds?.includes(variant.id)) {
                console.log(`Variant ${variant.id} is eligible for the coupon`);

                applyCoupon = true

            }
            else if (couponProductIds?.includes(variant.product.id)) {
                console.log(`Product ${variant.product.id} is eligible for the coupon`);
                applyCoupon = true
            }
            else if (couponCategoryIds?.includes(variant.product.category_id)) {
                console.log(`Category ${variant.product.category_id} is eligible for the coupon`);
                applyCoupon = true
            }
            else if (couponCollectionIds?.includes(variant.product.collection_id!)) {
                console.log(`Collection ${variant.product.collection_id} is eligible for the coupon`);
                applyCoupon = true
            }

        })

        console.log(coupon.code)
        if (coupon.code == "FREE SHIPPING") {
            applyCoupon = true
        }


        if (!applyCoupon) {
            return NextResponse.json(
                { message: "No items in your cart are eligible for this coupon." },
                { status: 400 }
            );
        }

        await db.cart.update({
            where: { profile_id: session.user.profileId },
            data: {
                discountCode: coupon.code,
                discountAmount: coupon.value,
            },
        })





        return NextResponse.json(
            {
                message: "Coupon is valid and can be applied.",
                coupon,
            },
            { status: 200 }
        );
    } catch (error) {
        console.error("Error applying coupon:", error);
        return NextResponse.json(
            { message: "Something went wrong while validating the coupon." },
            { status: 500 }
        );
    }
}



export async function DELETE(request: Request) {
    try {
        const session = await getServerSession(authOptions);
        if (!session?.user?.uuid) {
            return NextResponse.json(
                { message: "You are not authorized!" },
                { status: 403 }
            );
        }


        await db.cart.update({
            where: { profile_id: session.user.profileId },
            data: { discountCode: null, discountAmount: 0 },
        })

        return NextResponse.json({ message: "Coupon removed successfully." }, { status: 200 })


    }
    catch (error) {
        console.error("Error removing coupon:", error);
        return NextResponse.json(
            { message: "Something went wrong while removing the coupon." },
            { status: 500 }
        );
    }
}