import { Injectable } from "@nestjs/common"; import { InjectModel } from "@nestjs/sequelize"; import { Cart } from "./entities/cart.entity"; import { HttpException, HttpStatus } from "@nestjs/common"; import { CartResponse } from "./cart.response"; import { User } from "src/users/entities/user.entity"; import { Product } from "src/products/entities/product.entity"; @Injectable() export class CartService { constructor( @InjectModel(Cart) private readonly cartModel: typeof Cart, @InjectModel(User) private readonly userModel: typeof User, @InjectModel(Product) private readonly productModel: typeof Product, ) {} async addToCart(userId: number, productId: number, quantity: number): Promise { try { if (!userId || !productId || !quantity) { throw new HttpException("Missing required parameters: userId, productId, and quantity are required.", HttpStatus.BAD_REQUEST); } const user = await this.userModel.findByPk(userId); if (!user) { throw new HttpException("User not found!", HttpStatus.NOT_FOUND); } const product = await this.productModel.findByPk(productId); if (!product) { throw new HttpException("Product not found!", HttpStatus.NOT_FOUND); } const existingCartItem = await this.cartModel.findOne({ where: { userId, productId }, }); if (existingCartItem) { existingCartItem.quantity += Number(quantity); await existingCartItem.save(); return { message: "Product quantity updated in cart successfully!", cartItem: existingCartItem, }; } const newCartItem = await this.cartModel.create({ userId, productId, quantity }); return { message: "Product added to cart successfully!", cartItem: newCartItem, }; } catch (error) { // Enhanced error handling if (error instanceof HttpException) { throw error; } throw new HttpException(`An error occurred while adding the product to the cart: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR); } } }