import { Decimal } from "decimal.js";
import type { PurchaseOrderReceiptStatus, PurchaseOrderBillingStatus } from "../generated/enums";

export interface LineProgress {
  quantity: string;
  receivedQuantity?: string | null;
  billedQuantity?: string | null;
}

function summarizeOrderProgress(lines: LineProgress[]) {
  let totalOrdered = new Decimal(0);
  let totalReceived = new Decimal(0);
  let totalBilled = new Decimal(0);

  for (const line of lines) {
    totalOrdered = totalOrdered.plus(line.quantity);
    totalReceived = totalReceived.plus(line.receivedQuantity ?? "0");
    totalBilled = totalBilled.plus(line.billedQuantity ?? "0");
  }

  return { totalOrdered, totalReceived, totalBilled };
}

export function deriveReceiptStatus(lines: LineProgress[]): PurchaseOrderReceiptStatus {
  const { totalOrdered, totalReceived } = summarizeOrderProgress(lines);
  if (totalOrdered.isZero()) return "NOT_RECEIVED";
  if (totalReceived.gte(totalOrdered)) return "RECEIVED";
  if (totalReceived.gt(0)) return "PARTIALLY_RECEIVED";
  return "NOT_RECEIVED";
}

export function deriveBillingStatus(lines: LineProgress[]): PurchaseOrderBillingStatus {
  const { totalOrdered, totalBilled } = summarizeOrderProgress(lines);
  if (totalOrdered.isZero()) return "NOT_BILLED";
  if (totalBilled.gte(totalOrdered)) return "BILLED";
  if (totalBilled.gt(0)) return "PARTIALLY_BILLED";
  return "NOT_BILLED";
}
