/**
 * Stripe PaymentIntent line-item metadata helpers — SKU-keyed labelling.
 *
 * Stripe PaymentIntents (as opposed to Checkout Sessions) do not support a
 * `line_items` array.  Instead we encode SKU identity into `description` and
 * `metadata` so that the Stripe dashboard and reconciliation tooling can
 * identify exactly which SKU variant was purchased.
 */

import { pickLocalized } from '@/lib/i18n';
import type { DealWithSkus } from '@/server/domain/variants/read.js';

/**
 * Build a human-readable SKU label from the deal's variant axes.
 *
 * Examples:
 *   - No-variant deal   → null  (caller should fall back to dealTitle)
 *   - SIZE=L, COLOR=Red → "L · Red"
 *   - TIMESLOT only     → "19:00–21:00"
 *
 * @param dealWithSkus  Full variant data for the deal.
 * @param dealSkuId     The SKU selected by the customer.
 * @param locale        'he' (default) or 'en' — controls option label language.
 * @returns             Human-readable label string, or null when the deal has
 *                      no variant axes (no-variant / scalar deal).
 */
export function buildSkuLabel(
  dealWithSkus: DealWithSkus,
  dealSkuId: string,
  locale: 'he' | 'en' = 'he',
): string | null {
  const { axes, skus } = dealWithSkus;

  if (axes.length === 0) {
    // No variant axes — scalar deal, no label needed.
    return null;
  }

  const sku = skus.find((s) => s.id === dealSkuId);
  if (!sku) {
    throw new Error(`SKU_NOT_FOUND:${dealSkuId}`);
  }

  const allOptions = axes.flatMap((a) => a.options);
  const parts = sku.optionIds
    .map((oid) => {
      const opt = allOptions.find((o) => o.id === oid);
      return opt ? pickLocalized(opt, locale, 'label') : '';
    })
    .filter(Boolean);

  return parts.join(' · ') || null;
}

/**
 * Build the `description` string for a Stripe PaymentIntent.
 *
 * Format:
 *   - Variant deal  → "<dealTitle> — <skuLabel>"
 *   - Scalar deal   → "<dealTitle>"
 */
export function buildStripeDescription(dealTitle: string, skuLabel: string | null): string {
  return skuLabel ? `${dealTitle} — ${skuLabel}` : dealTitle;
}
