import {
  RemissionItem,
  RemissionListType,
  ReturnItem,
  ReturnSuggestion,
} from '@isa/remission/data-access';

/**
 * Calculates the stock to remit based on the remission item and available stock.
 * Uses the getStockToRemit helper function.
 * @param {Object} params - The parameters for the calculation
 * @param {RemissionItem} params.remissionItem - The remission item to calculate stock for
 * @param {RemissionListType} params.remissionListType - The type of the remission list
 * @param {number} params.availableStock - The available stock for the item
 * @return {number} The calculated stock to remit
 */
export const getStockToRemit = ({
  remissionItem,
  remissionListType,
  availableStock,
}: {
  remissionItem: RemissionItem;
  remissionListType: RemissionListType;
  availableStock: number;
}): number => {
  const remainingQuantityInStock = remissionItem?.remainingQuantityInStock;
  let predefinedReturnQuantity: number | undefined = undefined;

  if (remissionListType === RemissionListType.Pflicht) {
    predefinedReturnQuantity = (remissionItem as ReturnItem)
      ?.predefinedReturnQuantity;
  }

  if (remissionListType === RemissionListType.Abteilung) {
    predefinedReturnQuantity = (remissionItem as ReturnSuggestion)?.returnItem
      ?.data?.predefinedReturnQuantity;
  }

  return calculateStockToRemit({
    availableStock,
    remainingQuantityInStock,
    predefinedReturnQuantity,
  });
};

/**
 * Calculates the stock to remit based on available stock, predefined return quantity,
 * and remaining quantity in stock.
 *
 * @param {Object} params - The parameters for the calculation.
 * @param {number} params.availableStock - The total available stock.
 * @param {number} [params.predefinedReturnQuantity] - The predefined return quantity, if any.
 * @param {number} [params.remainingQuantityInStock] - The remaining quantity in stock, if any.
 * @returns {number} - The calculated stock to remit.
 */
export const calculateStockToRemit = ({
  availableStock,
  predefinedReturnQuantity,
  remainingQuantityInStock,
}: {
  availableStock: number;
  predefinedReturnQuantity?: number;
  remainingQuantityInStock?: number;
}): number => {
  // #5269 Fix - Mache Näherungskalkulation, wenn kein predefinedReturnQuantity Wert vom Backend kommt
  if (predefinedReturnQuantity === undefined) {
    const stockToRemit = availableStock - (remainingQuantityInStock ?? 0);
    return stockToRemit < 0 ? 0 : stockToRemit;
  }

  // #5280 Fix - Ansonsten nehme immer den kalkulierten Wert vom Backend her auch wenn dieser 0 ist
  return predefinedReturnQuantity;
};
