import { NextRequest, NextResponse } from "next/server";
import { authOptions } from "@/app/api/auth/[...nextauth]/auth-options";
import { getServerSession } from "next-auth";
import { db } from "@/lib/db";
import { Prisma } from "@prisma/client";
import { getLogger } from "@/utils/logger";

const logger = getLogger("/api/cart/addItem/[variantId]")


export const POST = async (request: NextRequest, { params }: { params: { variantId: string } }) => {
  try {
    const session = await getServerSession(authOptions);

    const user = await db.user.findUnique({
      where: {
        uuid: session?.user.uuid
      },
      include: {
        profile: {
          include: {
            Cart: true
          }
        },

      },
    })

    const profileId = user?.profile?.id

    const cart_id = user?.profile?.Cart?.id

    if (!profileId || !cart_id) {
      return NextResponse.json({ mssg: 'Not authorized or cart not found' }, { status: 403 })
    }

    const cartItem = await db.cartItem.findUnique({
      where: {
        cart_id_variant_id: {
          cart_id: cart_id as number,
          variant_id: parseInt(params.variantId)
        }
      }
    })

    const variant = await db.productVariant.findUnique({
      where: {
        id: parseInt(params.variantId)
      }
    })

    if (!cartItem) {
      const newCartItem = await db.cartItem.create({
        data: {
          variant_id: parseInt(params.variantId),
          cart_id: cart_id,
          quantity: 1,
          price: variant?.special_price ?? 0
        },
        include: {
          variant: {
            include: {
              variant_images: true
            }
          }
        }
      })

      const updatedCart = await db.cart.update({
        where: {
          id: user.profile?.Cart?.id
        },
        data: {
          totalPrice: (user.profile?.Cart?.totalPrice ?? 0) + newCartItem.price * newCartItem.quantity,
          totalQuantity: (user.profile?.Cart?.totalQuantity ?? 0) + 1
        },
        include: {
          CartItem: {
            include: {
              variant: {
                include: {
                  variant_images: true
                }
              }
            }
          }
        }
      })

      return NextResponse.json({ mssg: newCartItem, updatedCart }, { status: 200 })
    }

    const updatedCartItem = await db.cartItem.update({
      where: {
        cart_id_variant_id: {
          cart_id: cart_id as number,
          variant_id: parseInt(params.variantId)
        }
      },
      data: {
        quantity: (cartItem?.quantity ?? 0) + 1,
        price: cartItem.price
      },
      include: {
        variant: {
          include: {
            variant_images: true
          }
        }
      }
    })

    console.log(updatedCartItem)
    console.log(user.profile?.Cart?.totalPrice)
    console.log(cartItem.price)
    console.log(user.profile?.Cart?.totalQuantity)



    const updatedCart = await db.cart.update({
      where: {
        id: user.profile?.Cart?.id
      },
      data: {
        totalPrice: (user.profile?.Cart?.totalPrice ?? 0) + cartItem.price,
        totalQuantity: (user.profile?.Cart?.totalQuantity ?? 0) + 1
      },
      include: {
        CartItem: {
          orderBy: {
            price: Prisma.SortOrder.desc
          },
          include: {
            variant: {
              include: {
                variant_images: true
              }
            }
          }
        }
      }
    })

    return NextResponse.json({ mssg: updatedCartItem, updatedCart }, { status: 200 })
  }
  catch (error: any) {

    logger.error("Failed to add item to the cart", {
      error: error?.config?.data ?? error?.message ?? "Unknown error"
    });
    return new NextResponse("Internal server error", { status: 500 })
  }
}