/**
 * Platform-funded commission computation.
 *
 * INVARIANT: Vendor payout is NEVER reduced. Platform absorbs the cost.
 *
 * Commission rates (tier1_pct, tier2_pct, tier3_pct, referral_pct) are
 * % of the full purchase amount (amountPaidAgorot), NOT % of platformNet.
 * Example: tier1_pct=3 → affiliate earns floor(amountPaid * 3 / 100).
 *
 * Tier is resolved ONCE at accrual time (trailing-30-day purchase count)
 * and stored as resolved_pct on the credit_ledger row. No recomputation at maturation.
 *
 * Self-deal block (§M.10a): if the referrer is the vendor owner,
 * commission amount_agorot = 0 and SELF_VENDOR_PURCHASE is logged.
 * Referee referral_reward still applies normally.
 */

import { floorAgorotPercent } from '@/lib/money';
import type { ReferralSettings } from './settings.js';

export const PLATFORM_FEE_PCT = 10 as const;

/** Compute the platform's gross net from a paid amount (used for invoicing/reporting). */
export function computePlatformNet(
  amountPaidAgorot: number,
  feePct: number = PLATFORM_FEE_PCT,
): number {
  return floorAgorotPercent(amountPaidAgorot, feePct);
}

/**
 * Resolve the affiliate tier pct (% of sale) for a given trailing-30-day purchase count.
 * Tier locked at accrual — call this once per purchase, store the result as resolved_pct.
 *
 * monthlySales = COUNT of completed purchases attributed to this affiliate
 *   in the trailing 30 days, including the current purchase (it's committed before this call).
 */
export function resolveAffiliateTierPct(
  monthlySales: number,
  settings: Pick<
    ReferralSettings,
    'tier1Pct' | 'tier2Pct' | 'tier3Pct' | 'tier2MinSales' | 'tier3MinSales'
  >,
): number {
  if (monthlySales >= settings.tier3MinSales) return settings.tier3Pct;
  if (monthlySales >= settings.tier2MinSales) return settings.tier2Pct;
  return settings.tier1Pct;
}

/**
 * Compute affiliate commission = floor(amountPaid * resolvedTierPct / 100).
 * resolvedTierPct comes from resolveAffiliateTierPct() — it is % of sale.
 */
export function computeAffiliateCommission(
  amountPaidAgorot: number,
  resolvedTierPct: number,
): number {
  if (resolvedTierPct <= 0 || amountPaidAgorot <= 0) return 0;
  return floorAgorotPercent(amountPaidAgorot, Math.min(resolvedTierPct, 10));
}

/**
 * Compute referral store credit = floor(amountPaid * referralPct / 100).
 * referralPct from settings (% of sale). Applied to referrer's wallet as store credit.
 */
export function computeReferralCommission(
  amountPaidAgorot: number,
  settings: Pick<ReferralSettings, 'referralPct'>,
): number {
  if (settings.referralPct <= 0 || amountPaidAgorot <= 0) return 0;
  return floorAgorotPercent(amountPaidAgorot, Math.min(settings.referralPct, 10));
}

/**
 * Determine whether a purchase is a self-vendor scenario (§M.10a).
 * Returns true when the referrer's userId matches the vendor's ownerUserId.
 */
export function isSelfVendorPurchase(referrerUserId: string, vendorOwnerUserId: string): boolean {
  return referrerUserId === vendorOwnerUserId;
}

export const SELF_VENDOR_PURCHASE = 'SELF_VENDOR_PURCHASE' as const;
