import { ProductInventoryDto, ProductModel, ProductPriceDto } from "@insite/client-framework/Types/ApiModels";

export interface ProductInfo {
    productId: string;
    qtyOrdered: number;
    unitOfMeasure: string;
    pricing?: ProductPriceDto;
    inventory?: ProductInventoryDto;
    failedToLoadPricing?: true;
    failedToLoadInventory?: true;
    productDetailPath: string;
}

export function createFromProduct(product: ProductModel): ProductInfo {
    const unitOfMeasure =
        (product.customerUnitOfMeasure || product.unitOfMeasures?.find(o => o.isDefault)?.unitOfMeasure) ?? "";
    let qtyAdjusted = Math.max(product.minimumOrderQty, 1);
    if (unitOfMeasure) {
        const uom = product.unitOfMeasures?.find(o => o.unitOfMeasure === unitOfMeasure);
        if (uom && product.minimumOrderQty > 0 && uom.qtyPerBaseUnitOfMeasure > 0) {
            qtyAdjusted = Math.ceil(product.minimumOrderQty / uom.qtyPerBaseUnitOfMeasure);
        }
    }
    return {
        productId: product.id,
        qtyOrdered: qtyAdjusted,
        unitOfMeasure,
        productDetailPath: product.canonicalUrl,
    };
}
