import { NextRequest, NextResponse } from "next/server";
import db from "@/lib/db";
import { authOptions } from "@/app/api/auth/[...nextauth]/auth-options";
import { getServerSession } from "next-auth";
import { getLogger } from "@/utils/logger";
import { Prisma } from "@prisma/client";

const logger = getLogger('/api/cart');

export async function POST(request: NextRequest) {
    try {

        const req = await request.json()
        const session = await getServerSession(authOptions);

        // console.log(session?.user.uuid)
        // console.log(req)

        const items = req.items

        const user = await db.user.findUnique({
            where: {
                uuid: session?.user.uuid
            },
            include: {
                profile: true
            }

        })

        if (user?.profile?.id === undefined) {
            return NextResponse.json({ error: 'User profile id not found' }, { status: 400 });
        }

        var cart = await db.cart.findFirst({
            where: {
                profile_id: user?.profile?.id
            }
        })

        if (!cart) {

            cart = await db.cart.create({
                data: {
                    profile_id: user.profile.id,
                    totalPrice: 0,
                    totalQuantity: 0
                }
            })
        }

        if (!cart) {
            return NextResponse.json({ error: 'Cart not found or could not be created' }, { status: 400 });
        }

        const cartItems = await db.cartItem.createMany({
            data: items.map((item: any) => ({
                price: item.price,
                variant_id: item.variant.id,
                cart_id: cart!.id
            }))
        })

        await db.cart.update({
            where: {
                id: cart.id
            },
            data: {
                totalPrice: items.reduce((acc: number, item: any) => acc + item.price * item.quantity, 0),
                totalQuantity: items.reduce((acc: number, item: any) => acc + item.quantity, 0)
            }
        })


        return NextResponse.json({ mssg: 'Cart updated successfully' }, { status: 200 })

    }
    catch (error: any) {
        logger.error("Failed to create a cart", {
            error: error?.config?.data ?? error?.message ?? "Unknown error"
        });

        return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
    }
}


export async function GET(request: NextRequest) {
    try {
        const session = await getServerSession(authOptions);

        const user = await db.user.findUnique({
            where: {
                uuid: session?.user.uuid
            },
            include: {
                profile: true
            }

        })

        if (user?.profile?.id === undefined) {
            return NextResponse.json({ error: 'User profile id not found' }, { status: 400 });
        }

        var cart = await db.cart.findUnique({
            where: {
                profile_id: session?.user.profileId
            },
            include: {
                CartItem: {
                    include: {
                        variant: {
                            include: {
                                variant_images: true
                            }
                        }
                    }
                }
            }
        })

        if (!cart) {
            cart = await db.cart.create({
                data: {
                    profile_id: user.profile.id,
                },
                include: {
                    CartItem: {
                        include: {
                            variant: {
                                include: {
                                    variant_images: true
                                }
                            }
                        }
                    }

                }
            })
        }


        var totalPrice = 0
        var totalQuantity = 0

        var stockOut = false

        cart.CartItem.forEach(item => {
            totalPrice += item.price * item.quantity
            totalQuantity += item.quantity

            // Check if the variant quantity is less than cart item quantity
            if (item.variant.quantity <= 0) {
                stockOut = true
            }
        })

        if (!cart) {
            return NextResponse.json({ error: 'Cart not found or could not be created' }, { status: 400 });
        }

        const updatedCart = await db.cart.update({
            where: {
                id: cart.id
            },
            data: {
                totalPrice: totalPrice,
                totalQuantity: totalQuantity
            },
            include: {
                CartItem: {
                    orderBy: {
                        price: Prisma.SortOrder.desc
                    },
                    include: {
                        variant: {
                            include: {
                                variant_images: true
                            }
                        }
                    }
                }
            }
        })

        return NextResponse.json({
            mssg: {
                cart: updatedCart,
                totalPrice: totalPrice,
                totalQuantity: totalQuantity,
                stockOut: stockOut

            }
        }, { status: 200 })


    }
    catch (error: any) {
        logger.error(`Failed to fetch an user cart`, {
            error: error?.config?.data ?? error?.message ?? "Unknown error"
        });

        return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
    }
}
