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";

const logger = getLogger('/api/cart/mergeCart');

export async function POST(request: NextRequest) {
    try {
        const req = await request.json()

        console.log('INSIDE MERGE CART API')

        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: user?.profile?.id
            }
        })

        console.log(req)

        if (!cart) {
            cart = await db.cart.create({
                data: {
                    profile_id: user.profile.id,
                }
            })
        }

        const items = req.items

        items.forEach(async (item: any) => {

            const cartItem = await db.cartItem.findUnique({
                where: {
                    cart_id_variant_id: {
                        cart_id: cart!.id,
                        variant_id: item.variant.id
                    }
                }
            })

            if (!cartItem) {
                await db.cartItem.create({
                    data: {
                        price: item.price,
                        quantity: item.quantity,
                        variant_id: item.variant.id,
                        cart_id: cart!.id
                    }
                })
            } else {
                await db.cartItem.update({
                    where: {
                        id: cartItem.id
                    },
                    data: {
                        quantity: cartItem.quantity + 1
                    }
                })
            }

        })


        return NextResponse.json({ mssg: "MERGE CART API" }, { status: 200 })

    }
    catch (error: any) {
        logger.error("Failed to merge a cart", {
            error: error?.config?.data ?? error?.message ?? "Unknown error"
        });
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
}