import type { PromoClaim } from '@/server/promo/types.js';
import { floorAgorotPercent } from '@/lib/money';

/**
 * Compute the Stripe PaymentIntent `amount` and `application_fee_amount`
 * fields given an optional promo claim (spec §5.4).
 *
 * - No promo: amount = T, fee = F = floor(T * platformFeePct%)
 * - Vendor-funded: amount = T − D, fee = F on ORIGINAL T (vendor absorbs discount)
 * - Platform-funded: amount = T − D, fee = F − D (platform absorbs discount; gate ensures D ≤ F)
 *
 * @param platformFeePct  Platform fee as a whole-number percentage (e.g. 10 = 10%).
 *                        Read from env.PLATFORM_FEE_PCT at the call site; never hardcode.
 */
export function computeStripeAmounts(
  totalAgorot: number,
  promoClaim: PromoClaim | undefined,
  platformFeePct: number = 10,
): { amount: number; applicationFeeAmount: number } {
  const F = floorAgorotPercent(totalAgorot, platformFeePct);

  if (!promoClaim) return { amount: totalAgorot, applicationFeeAmount: Math.max(0, F) };

  const D = promoClaim.discountAgorot;

  if (promoClaim.funder === 'vendor') {
    // Vendor absorbs full discount: customer pays T−D, platform still collects F on original T
    return { amount: totalAgorot - D, applicationFeeAmount: Math.max(0, F) };
  }

  // Platform-funded: gate upstream guarantees D ≤ F; clamp defends against env/fee drift.
  return { amount: totalAgorot - D, applicationFeeAmount: Math.max(0, F - D) };
}
