import { Decimal } from "decimal.js";

export type TransferOrderProgressLine = {
  orderedQuantity: string;
  shippedQuantity: string;
  receivedQuantity: string;
};

export type TransferOrderShippingStatus = "NOT_SHIPPED" | "PARTIALLY_SHIPPED" | "SHIPPED";
export type TransferOrderReceivingStatus = "NOT_RECEIVED" | "PARTIALLY_RECEIVED" | "RECEIVED";

export function getTransferOrderShippingStatus(lines: TransferOrderProgressLine[]) {
  if (lines.length === 0) {
    return "NOT_SHIPPED" satisfies TransferOrderShippingStatus;
  }
  if (lines.every((line) => new Decimal(line.shippedQuantity).eq(0))) {
    return "NOT_SHIPPED" satisfies TransferOrderShippingStatus;
  }
  if (
    lines.every((line) => new Decimal(line.shippedQuantity).gte(new Decimal(line.orderedQuantity)))
  ) {
    return "SHIPPED" satisfies TransferOrderShippingStatus;
  }
  return "PARTIALLY_SHIPPED" satisfies TransferOrderShippingStatus;
}

export function getTransferOrderReceivingStatus(lines: TransferOrderProgressLine[]) {
  if (lines.length === 0) {
    return "NOT_RECEIVED" satisfies TransferOrderReceivingStatus;
  }
  if (lines.every((line) => new Decimal(line.receivedQuantity).eq(0))) {
    return "NOT_RECEIVED" satisfies TransferOrderReceivingStatus;
  }
  if (
    lines.every((line) => new Decimal(line.receivedQuantity).gte(new Decimal(line.orderedQuantity)))
  ) {
    return "RECEIVED" satisfies TransferOrderReceivingStatus;
  }
  return "PARTIALLY_RECEIVED" satisfies TransferOrderReceivingStatus;
}

export function isTransferOrderFullyReceived(lines: TransferOrderProgressLine[]) {
  return (
    lines.length > 0 &&
    lines.every((line) => new Decimal(line.receivedQuantity).gte(new Decimal(line.orderedQuantity)))
  );
}

export function isTransferOrderInTransitClear(lines: TransferOrderProgressLine[]) {
  return lines.every((line) => new Decimal(line.shippedQuantity).eq(line.receivedQuantity));
}

export function isPositiveDecimal(value: string) {
  try {
    return new Decimal(value).gt(0);
  } catch {
    return false;
  }
}
