/**
 * Shared promo-code formatting helpers used by both admin and vendor UIs.
 */
import { formatAgorotShekels } from '@/lib/money.js';
import { enumLabel } from '@/lib/enums/enum-labels';
import { getT, type Locale } from '@/lib/i18n';
import { interpolate } from '@/lib/i18n/interpolate';

interface PromoValueFields {
  kind: string;
  valueBps: number | null;
  valueAmount: number | null;
  bogoBuy: number | null;
  bogoGetFree: number | null;
}

function formatPercentBps(valueBps: number): string {
  const pct = valueBps / 100;
  const fixed = pct.toFixed(2).replace(/\.?0+$/, '');
  return `${fixed}%`;
}

/** Format a promo code's value for display (e.g. "20%", "₪15.00", "Buy 2 get 1 free"). */
export function formatPromoValue(row: PromoValueFields, locale: Locale = 'he'): string {
  if (row.kind === 'percentage' && row.valueBps != null) {
    return formatPercentBps(row.valueBps);
  }
  if (row.kind === 'fixed_amount' && row.valueAmount != null) {
    return formatAgorotShekels(row.valueAmount);
  }
  if (row.kind === 'bogo' && row.bogoBuy != null && row.bogoGetFree != null) {
    const t = getT(locale, 'promo_codes') as (key: string) => string;
    return interpolate(t('admin.table.bogo_value'), {
      buy: String(row.bogoBuy),
      free: String(row.bogoGetFree),
    });
  }
  return '—';
}

/** Map a promo status string to a Badge tone. */
export function promoStatusTone(status: string): 'success' | 'warning' | 'neutral' {
  if (status === 'active') return 'success';
  if (status === 'paused') return 'warning';
  return 'neutral';
}

interface PromoStatusFields {
  status: string;
  validUntil: string | null;
}

/** Localized promo status label for vendor/admin lists. */
export function formatPromoStatus(
  row: PromoStatusFields,
  locale: Locale = 'he',
  audience: 'admin' | 'vendor' = 'vendor',
): string {
  if (row.validUntil && new Date(row.validUntil) < new Date() && row.status === 'active') {
    return enumLabel('promo_status', 'expired', locale, audience);
  }
  return enumLabel('promo_status', row.status, locale, audience);
}
