/**
 * Cardcom payment gateway adapter — payment-gateway-adapters (wave-10 leaf 5).
 *
 * Cardcom (https://www.cardcom.solutions/) is a leading Israeli payment processor.
 * Generates a hosted payment page URL for invoice collection.
 *
 * STUB — FAIL-CLOSED: not yet implemented. generatePaymentLink THROWS so no
 * route can serve a real-looking mock URL to a paying customer. Replace the
 * internals with the real Cardcom LowProfile call (commented below) when
 * credentials are available; remove the throw only together with that work.
 * Spec contract (2026-05-31-payment-gateway-adapters.md §"only built gateways"):
 * a stub adapter must not be reachable in production — this throw enforces it.
 *
 * ACCEPTED-RISK (S9-i2-004): No inbound webhook verification or settlement path
 * exists while this adapter is a stub. Before production use, add signed webhook
 * routes, provider re-fetch confirmation, and idempotent recordInvoicePayment.
 *
 * Cardcom API docs: https://kb.cardcom.solutions/article/AA-00401
 * Required config: terminalNumber, apiName, apiPassword
 */

export interface CardcomConfig {
  terminalNumber: string // Cardcom terminal number
  apiName: string // API username
  apiPassword: string // API password
}

export interface PaymentLinkResult {
  url: string
  expiresAt: string | null
}

/**
 * Generate a Cardcom hosted payment page URL for an invoice.
 *
 * STUB — FAIL-CLOSED: throws until the real Cardcom LowProfile call replaces it.
 */
export async function generatePaymentLink(
  config: CardcomConfig,
  invoice: {
    id: string
    invoiceNumber: string | null
    amount: string
    currency: string
    customerName: string
    description?: string
  },
): Promise<PaymentLinkResult> {
  console.info('[cardcom] Generating payment link (stub)', {
    invoiceId: invoice.id,
    invoiceNumber: invoice.invoiceNumber,
    amount: invoice.amount,
    currency: invoice.currency,
    // Never log apiPassword
    terminalNumber: config.terminalNumber,
  })

  /*
   * Real Cardcom LowProfile API call:
   *
   * const params = new URLSearchParams({
   *   TerminalNumber: config.terminalNumber,
   *   ApiName: config.apiName,
   *   ApiPassword: config.apiPassword,
   *   SumToBill: invoice.amount,
   *   CoinID: '1', // 1 = ILS
   *   MaxPayments: '1',
   *   ProductName: invoice.description ?? `Invoice ${invoice.invoiceNumber ?? invoice.id}`,
   *   SuccessRedirectUrl: `${process.env['APP_URL']}/invoices/${invoice.id}?payment=success`,
   *   ErrorRedirectUrl: `${process.env['APP_URL']}/invoices/${invoice.id}?payment=error`,
   *   Indication2: invoice.id,
   * })
   * const res = await fetch(`https://secure.cardcom.solutions/Interface/LowProfile.aspx?${params}`)
   * const text = await res.text()
   * // Parse response: "ResponseCode=0&LowProfileCode=...&url=https://..."
   * const parsed = Object.fromEntries(new URLSearchParams(text))
   * if (parsed['ResponseCode'] !== '0') throw new Error(`Cardcom error: ${parsed['Description']}`)
   * return { url: parsed['url']!, expiresAt: null }
   */

  // FAIL-CLOSED: the Cardcom adapter is a stub with no real API call. Returning a
  // mock `secure.cardcom.solutions/mock/...` URL would hand a paying customer a
  // plausible but fake payment link. Throw instead — both live routes (invoices/
  // payment-link and portal/invoices) wrap this in try/catch and surface a 502.
  throw new Error(
    'Cardcom payment gateway is not configured for production. ' +
      'No live Cardcom integration is implemented; refusing to issue a mock payment link.',
  )
}
