const Cart = class Cart {
    constructor(cart) {
        this.cartItems = cart;
        this.total = 0;
    }
    async addToCart(cart) {
        const alreadyExists = await this.checkProductExists(cart.id)
        if (alreadyExists) {
            const index = this.cartItems.findIndex(({ id }) => id === cart.id)
            var oldQty = this.cartItems[index].quantity
            var newQty = oldQty + cart.quantity
            this.cartItems[index].quantity = newQty
        } else {
            this.cartItems.push(cart)
        }
        await this.calculateTotal()
        return this.getCart()
    }

    async removeQuantityFromCart(cart) {
        const alreadyExists = await this.checkProductExists(cart.id);
        if (alreadyExists) {
            const index = this.cartItems.findIndex(({ id }) => id === cart.id)
            var oldQty = this.cartItems[index].quantity
            if (oldQty === 1) {
                this.removeFromCart(cart)
            } else {
                var newQty = oldQty - cart.quantity
                this.cartItems[index].quantity = newQty
            }
            await this.calculateTotal()
            return this.getCart()
        }
        return this.getCart()
    }

    async buyNow(cart) {
        const alreadyExists = await this.checkProductExists(cart.id)
        if (!alreadyExists) {
            this.cartItems.push(cart)
        }
        await this.calculateTotal()
        return this.getCart()
    }

    async removeFromCart(cart) {
        this.cartItems = [...this.cartItems].filter((element) => element.id !== cart.id);
        await this.calculateTotal();
        return this.getCart()
    }

    async checkProductExists(id) {
        return await this.cartItems.filter((element) => element.id === id)[0] !== undefined;
    }

    async calculateTotal() {
        this.total = 0;
        await this.cartItems.map((item) => (this.total += item.price * item.quantity));
        return 1
    }

    getCart() {
        return this.cartItems;
    }

    clearCart() {
        this.cartItems = [];
    }
};

const CartItem = class CartItem {
    constructor(id, title, price, quantity, image) {
        this.id = id;
        this.title = title;
        this.price = price;
        this.quantity = quantity;
        this.image = image;
    }
};

module.exports = { Cart, CartItem };