import { DealProductSchema, DealSchema, ProductSchema } from "../../../../../client";

type UnaccountedValues = {
    boxId?: number | null;
    shippingProductId?: number | null;
}

type Props = {
    deal?: DealSchema;
    unaccountedValues: UnaccountedValues;
}

const getRestProducts = ({
                             deal,
                             unaccountedValues,
                         }: Props) => {
    const totalProducts = new Map(
        deal?.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 });
        }
    };

    deal?.boxes?.forEach((box) => {
        if (!box.product || box.id === unaccountedValues.boxId) return;
        accountProduct(box.product, box.quantity);
    });

    deal?.pallets?.forEach(pallet => {
        pallet.shippingProducts.forEach(shippingProduct => {
            if (shippingProduct.id === unaccountedValues.shippingProductId) return;
            accountProduct(shippingProduct.product, shippingProduct.quantity);
        });
        pallet.boxes.forEach((box) => {
            if (!box.product || box.id === unaccountedValues.boxId) return;
            accountProduct(box.product, box.quantity);
        });
    });

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

    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;