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/[variantId]")


export const DELETE = async (req: 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) {
      return NextResponse.json({ mssg: 'Not authorized' }, { status: 403 })
    }

    const deletedCartItems = await db.cartItem.delete({
      where: {
        cart_id_variant_id: {
          cart_id: cart_id as number,
          variant_id: parseInt(params.variantId)
        }
      }
    })


    return new NextResponse("CartItem deleted", { status: 200 });


  } catch (error: any) {
    if (error instanceof Prisma.PrismaClientValidationError) {
      logger.error("Prisma Validation Error ", { error: error.message });
    } else {
      logger.error("Error removing Cart Item", { errorMsg: error.message, errorData: error.config.data });
    }
    return new NextResponse("Internal server Error", { status: 500 });
  }
}


