// Automatic texts the platform sends to customers (shared client/server).
// Admins edit the wording and switch each one on or off on /admin/settings.

export type AutoSmsEvent = 'sign_in' | 'purchase'

export const AUTO_SMS_EVENTS: {
  key: AutoSmsEvent
  label: string
  description: string
  placeholders: { key: string; hint: string; sample: string }[]
  defaultTemplate: string
}[] = [
  {
    key: 'sign_in',
    label: 'Sign-in alert',
    description: 'Sent each time a customer signs in, so they know straight away if someone else used their account.',
    placeholders: [
      { key: 'name', hint: 'Customer name, or "there" if none', sample: 'Ama' },
      { key: 'email', hint: 'Sign-in email', sample: 'ama@example.com' },
      { key: 'device', hint: 'e.g. Chrome on Android', sample: 'Chrome on Android' },
      { key: 'time', hint: 'Sign-in time (Ghana)', sample: '25 Oct, 14:05' },
      { key: 'balance', hint: 'Credits left', sample: '1,200' },
    ],
    defaultTemplate:
      'Hi {name}, you just signed in to AkotoCreative SMS from {device} at {time}. Not you? Reset your password now.',
  },
  {
    key: 'purchase',
    label: 'Credit purchase',
    description: 'Sent once when a credit purchase is confirmed by Moolre.',
    placeholders: [
      { key: 'name', hint: 'Customer name, or "there" if none', sample: 'Ama' },
      { key: 'credits', hint: 'Credits bought', sample: '5,000' },
      { key: 'amount', hint: 'Amount paid', sample: 'GH₵ 150.00' },
      { key: 'bundle', hint: 'Bundle name', sample: 'Business' },
      { key: 'balance', hint: 'New balance', sample: '6,200' },
      { key: 'reference', hint: 'Payment reference', sample: 'AKC-8F2K1' },
    ],
    defaultTemplate:
      'Hi {name}, {credits} SMS credits have been added to your AkotoCreative account. Paid {amount}. New balance: {balance} credits. Ref {reference}.',
  },
]

export const AUTO_SMS_MAX_LENGTH = 459 // 3 SMS parts

// Fills {placeholders}; unknown ones are left as typed so mistakes are visible.
export function renderAutoSms(template: string, values: Record<string, string>) {
  return template.replace(/\{(\w+)\}/g, (match, key: string) => (key in values ? values[key] : match))
}

export function sampleValues(event: AutoSmsEvent) {
  const meta = AUTO_SMS_EVENTS.find((e) => e.key === event)!
  return Object.fromEntries(meta.placeholders.map((p) => [p.key, p.sample]))
}
