/**
 * CTA variant resolution + contact mailto builder — upgrade-upsell-modal (spec 36).
 *
 * Pure functions: no React, no side effects. Safe to import from server code.
 */
import { TenantTier } from '@zync/types'
import { tierRank } from './tier-card-data'

/**
 * Discriminated union describing which CTA variant to render on a tier card.
 *
 * - current       → disabled button "תוכנית נוכחית"
 * - downgrade     → CTA hidden entirely (cardTier < currentTier)
 * - checkout      → self-service upgrade → POST /api/zync-subscription/checkout
 * - contact       → enterprise / white_label — mailto link
 * - null_adapter  → payment provider not configured — mailto fallback
 */
export type CtaVariant =
  | 'current'
  | 'downgrade'
  | 'checkout'
  | 'contact'
  | 'null_adapter'

/**
 * Determines which CTA to display on a tier card.
 *
 * @param cardTier     - The tier this card represents.
 * @param currentTier  - The tenant's active subscription tier.
 * @param isNullAdapter - True when `zync_subscriptions.adapter === 'null'`.
 */
export function resolveCtaVariant(
  cardTier: TenantTier,
  currentTier: TenantTier,
  isNullAdapter: boolean,
): CtaVariant {
  if (cardTier === currentTier) return 'current'
  if (tierRank(cardTier) < tierRank(currentTier)) return 'downgrade'
  if (cardTier === TenantTier.ENTERPRISE || cardTier === TenantTier.WHITE_LABEL) return 'contact'
  if (isNullAdapter) return 'null_adapter'
  return 'checkout'
}

/**
 * Builds a mailto: href for the "Contact us" CTA.
 * Subject line is localised (Hebrew) and optionally includes a feature name.
 *
 * @param featureName  - Human-readable feature that triggered the modal (optional).
 * @param targetTier   - The tier being requested (affects subject wording).
 */
export function buildContactMailto(featureName?: string, targetTier?: TenantTier): string {
  const subject = encodeURIComponent(
    targetTier === TenantTier.ENTERPRISE
      ? `בקשת שדרוג ל-Enterprise${featureName ? ` — ${featureName}` : ''}`
      : `בקשת שדרוג לתוכנית${featureName ? ` — ${featureName}` : ''}`,
  )
  return `mailto:sales@zync.is?subject=${subject}`
}
