// The Moolre settings an admin can enter on /admin/settings. Shared by the
// client form and the server, so it holds no values, only the field list.
export const MOOLRE_FIELDS = [
  { key: 'apiUser', env: 'MOOLRE_API_USER', label: 'API username (X-API-USER)', secret: false, hint: 'Your Moolre username. Sent as the X-API-USER header on every collection request.' },
  { key: 'apiPubkey', env: 'MOOLRE_API_PUBKEY', label: 'Public API key (X-API-PUBKEY)', secret: true, hint: 'The Public key, not the Private key. Sent as X-API-PUBKEY to collect payments: creating payment links and checking payment status.' },
  { key: 'accountNumber', env: 'MOOLRE_ACCOUNT_NUMBER', label: 'Wallet account number', secret: false, hint: 'The Moolre wallet that receives customer payments.' },
  { key: 'businessEmail', env: 'MOOLRE_BUSINESS_EMAIL', label: 'Business email', secret: false, hint: 'Attached to every payment link.' },
  { key: 'vasKey', env: 'MOOLRE_VAS_KEY', label: 'VAS key (SMS)', secret: true, hint: 'Used to send SMS.' },
  { key: 'senderId', env: 'MOOLRE_SENDER_ID', label: 'Default sender ID', secret: false, hint: 'Optional. Up to 11 letters or numbers, exactly as approved on Moolre. Every customer may use it.' },
  { key: 'callbackSecret', env: 'MOOLRE_CALLBACK_SECRET', label: 'Webhook secret', secret: true, hint: 'The "Secret Key" from your Moolre dashboard. If set, payment callbacks must carry it.' },
] as const

export type MoolreFieldKey = (typeof MOOLRE_FIELDS)[number]['key']
export type MoolreEnvironment = 'live' | 'sandbox'

// Moolre keys are JWTs. Their payload only names the account they belong to
// (a public key carries userid and walletid, a VAS key carries vasid), so it is
// safe to read in the browser to catch keys pasted into the wrong field.
export type MoolreKeyInfo = { userid?: string; walletid?: string; vasid?: string; expiresAt?: string }

export function decodeMoolreKey(value: string): MoolreKeyInfo | null {
  const part = value.trim().split('.')[1]
  if (!part) return null
  try {
    const base64 = part.replace(/-/g, '+').replace(/_/g, '/')
    const json = JSON.parse(atob(base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), '=')))
    if (!json || typeof json !== 'object') return null
    const text = (v: unknown) => (typeof v === 'string' || typeof v === 'number' ? String(v) : undefined)
    return {
      userid: text(json.userid),
      walletid: text(json.walletid),
      vasid: text(json.vasid),
      expiresAt: typeof json.exp === 'number' ? new Date(json.exp * 1000).toISOString() : undefined,
    }
  } catch {
    return null
  }
}

// A warning for a key that is clearly in the wrong field or expired, or null.
export function moolreKeyProblem(field: 'apiPubkey' | 'vasKey', value: string): string | null {
  if (!value.trim()) return null
  const info = decodeMoolreKey(value)
  if (!info) return 'This does not look like a Moolre key. Copy it again from your Moolre dashboard.'
  if (info.expiresAt && new Date(info.expiresAt) < new Date()) return 'This key has expired. Generate a new one on Moolre.'
  if (field === 'apiPubkey' && info.vasid && !info.userid) return 'This looks like the SMS (VAS) key. Paste it under SMS instead.'
  if (field === 'vasKey' && info.userid && !info.vasid) return 'This looks like the Public API key. Paste it under Payments instead.'
  return null
}

// Moolre wallet account numbers end with the wallet ID the public key was
// issued for, so a mismatch usually means a phone number or another wallet.
export function walletMismatch(accountNumber: string, walletid: string | undefined) {
  const number = accountNumber.trim()
  return Boolean(number && walletid && !number.endsWith(walletid.padStart(6, '0')) && !number.endsWith(walletid))
}
