export type DiscountType = 'none' | 'amount' | 'percent' | 'senior_citizen' | 'pwd';

export const DISCOUNT_TYPES: { value: DiscountType; label: string }[] = [
  { value: 'none', label: 'No discount' },
  { value: 'amount', label: 'Fixed amount' },
  { value: 'percent', label: 'Percent' },
  { value: 'senior_citizen', label: 'Senior (20%)' },
  { value: 'pwd', label: 'PWD (20%)' },
];

export function computePosTotals(
  cart: { unit_price: number; quantity: number }[],
  opts: {
    discountType?: DiscountType;
    discountValue?: number;
    scPwdIdNumber?: string;
    taxRate?: number;
  } = {},
) {
  const subtotal = cart.reduce((sum, line) => sum + line.unit_price * line.quantity, 0);
  const discountType = opts.discountType || 'none';
  const discountValue = Number(opts.discountValue) || 0;
  let discount = 0;
  let effectiveTaxRate = Math.max(0, Number(opts.taxRate) || 0);

  if (discountType === 'senior_citizen' || discountType === 'pwd') {
    discount = round2(subtotal * 0.2);
    effectiveTaxRate = 0;
  } else if (discountType === 'percent') {
    discount = round2(subtotal * (Math.min(100, discountValue) / 100));
  } else if (discountType === 'amount') {
    discount = round2(Math.min(subtotal, discountValue));
  }

  const taxable = round2(Math.max(0, subtotal - discount));
  const tax = round2(taxable * (effectiveTaxRate / 100));
  const total = round2(taxable + tax);
  const scPwdRequired =
    (discountType === 'senior_citizen' || discountType === 'pwd') && !String(opts.scPwdIdNumber || '').trim();

  return { subtotal: round2(subtotal), discount, tax, total, scPwdRequired };
}

function round2(n: number) {
  return Math.round((n + Number.EPSILON) * 100) / 100;
}

export function isScPwdDiscount(discountType: DiscountType | string) {
  return discountType === 'senior_citizen' || discountType === 'pwd';
}

export function getDiscountLabel(discountType: DiscountType | string) {
  if (discountType === 'senior_citizen') return 'Senior Citizen discount (20%)';
  if (discountType === 'pwd') return 'PWD discount (20%)';
  const found = DISCOUNT_TYPES.find((t) => t.value === discountType);
  return found?.label || 'Discount';
}
