import type { DepositType, PaymentOption } from "@prisma/client";
import { addDays } from "./dates";

export type BatchLike = {
  opensAt: Date;
  closesAt: Date;
  capacity: number;
  heldQty: number;
  committedQty: number;
  manuallyClosed: boolean;
  paymentOption: PaymentOption;
  depositType: DepositType;
  depositValue: number;
  dispatchFrom: Date;
  dispatchTo: Date;
  balanceDueDays: number;
};

export type BatchState = "SCHEDULED" | "OPEN" | "CLOSED" | "SOLD_OUT";

export function remainingCapacity(b: Pick<BatchLike, "capacity" | "heldQty" | "committedQty">) {
  return Math.max(0, b.capacity - b.heldQty - b.committedQty);
}

export function batchState(b: BatchLike, now = new Date()): BatchState {
  if (b.manuallyClosed || now > b.closesAt) return "CLOSED";
  if (now < b.opensAt) return "SCHEDULED";
  if (remainingCapacity(b) <= 0) return "SOLD_OUT";
  return "OPEN";
}

/** Deposit charged per unit for a pre-order line. FULL_ONLY batches take no deposit (full price now). */
export function depositPerUnit(b: Pick<BatchLike, "paymentOption" | "depositType" | "depositValue">, unitPrice: number) {
  if (b.paymentOption === "FULL_ONLY") return unitPrice;
  if (b.depositType === "FIXED") return Math.min(Math.max(0, b.depositValue), unitPrice);
  const pct = Math.min(100, Math.max(0, b.depositValue));
  return Math.round((unitPrice * pct) / 100);
}

export function balanceDueDate(b: Pick<BatchLike, "dispatchFrom" | "balanceDueDays">) {
  return addDays(b.dispatchFrom, -b.balanceDueDays);
}

export function depositLabel(b: Pick<BatchLike, "paymentOption" | "depositType" | "depositValue">) {
  if (b.paymentOption === "FULL_ONLY") return "Full payment at order";
  const amount = b.depositType === "PERCENT" ? `${b.depositValue}% deposit` : `৳${b.depositValue.toLocaleString("en-IN")} deposit per item`;
  return b.paymentOption === "DEPOSIT_REQUIRED" ? `${amount}, balance before dispatch` : `${amount} or pay in full`;
}

export const STATE_LABEL: Record<BatchState, string> = {
  SCHEDULED: "Pre-order opens soon",
  OPEN: "Pre-order open",
  CLOSED: "Pre-order closed",
  SOLD_OUT: "Batch fully reserved",
};
