import { BoxSchema, CardProductSchema, CardSchema, ProductSchema } from "../../../../../client";


type Props = {
    card?: CardSchema;
    shippingProductId?: number | null;
}

const getRestProducts = ({
                             card,
                             shippingProductId,
                         }: Props) => {
    const totalProducts = new Map(
        card?.products.map(product => product && [product.product.id, product]),
    );

    const distributedProducts = new Map();

    const accountProduct = (product: ProductSchema, quantity: number) => {
        const productId = product.id;
        if (distributedProducts.has(productId)) {
            const prodData = distributedProducts.get(productId);
            distributedProducts.set(productId, { product, quantity: quantity + prodData.quantity });
        } else {
            distributedProducts.set(productId, { product, quantity });
        }
    };

    const accountBoxes = (boxes?: BoxSchema[]) => {
        boxes?.forEach((box) => {
            box.shippingProducts.forEach((shippingProduct) => {
                if (!shippingProduct.product || shippingProduct.id === shippingProductId) return;
                accountProduct(shippingProduct.product, shippingProduct.quantity);
            });
        });
    };

    accountBoxes(card?.boxes);

    card?.pallets?.forEach(pallet => {
        pallet.shippingProducts.forEach(shippingProduct => {
            if (shippingProduct.id === shippingProductId) return;
            accountProduct(shippingProduct.product, shippingProduct.quantity);
        });
        accountBoxes(pallet.boxes);
    });

    const restProducts = new Map<number, CardProductSchema>();

    totalProducts.entries().forEach(([key, product]) => {
        const distributedProduct = distributedProducts.get(key);
        if (distributedProduct) {
            if (product.quantity > distributedProduct.quantity) {
                const restQuantity = product.quantity - distributedProduct.quantity;
                restProducts.set(key, { ...product, quantity: restQuantity });
            }
        } else {
            restProducts.set(key, product);
        }
    });

    const restProductsSelectData: ProductSchema[] = [];

    restProducts.forEach(
        (restProduct) => {
            restProductsSelectData.push(restProduct.product);
        },
    );

    return {
        restProducts,
        restProductsSelectData,
    };
};

export default getRestProducts;