/**
 * Server-side notification text renderer — notification-center.
 *
 * Renders i18n keys + params into display strings for the /api/notifications/all
 * endpoint. Uses the same catalog keys as packages/ui/src/i18n/{he,en}.json.
 * Never leaks raw keys to the client.
 */

// ── Type-group map ─────────────────────────────────────────────────────────────
// Maps coarse UI filter categories to concrete NotificationType values.
// Values must match the canonical NotificationType union (packages/types).

export const typeGroupMap: Record<string, string[]> = {
  tasks: [
    'task_assigned',
    'task_updated',
    'task_comment',
    'task_status_changed',
    'task_due_soon',
    'task_overdue',
    'task_completed',
  ],
  invoices: [
    'invoice_paid',
    'invoice_overdue',
    'invoice_approved',
    'invoice_rejected',
    'invoice_sent',
    'invoice_viewed',
    'invoice_cancelled',
  ],
  tickets: [
    'ticket_created',
    'ticket_assigned',
    'ticket_replied',
    'ticket_sla_breach',
    'ticket_resolved',
    'ticket_escalated',
  ],
  mentions: ['mention'],
  system: [
    'system',
    'system_maintenance',
    'member_invited',
    'data_export_ready',
    'user_approved',
    'user_frozen',
    'user_invited',
    'user_joined',
    'role_changed',
    'trial_expiring',
    'subscription_expiring',
    'quota_warning',
    'payment_received',
    'payment_failed',
    'expense_submitted',
    'expense_approved',
    'expense_rejected',
    'project_created',
    'project_member_added',
    'project_deadline_approaching',
    'ai_suggestion_ready',
  ],
}

function candidateKeys(key: string, kind: 'title' | 'body'): string[] {
  const direct = key.trim()
  const compact = direct
    .replace(/^notifications?\./, '')
    .replace(/\.(title|body)$/, '')

  return [
    direct,
    `notification.${compact}.${kind}`,
    `notifications.${compact}.${kind}`,
    `notification.${compact}`,
    `notifications.${compact}`,
    compact,
  ]
}

// ── Inline catalogs ────────────────────────────────────────────────────────────
// Extracted from packages/ui/src/i18n/{he,en}.json.
// Template syntax: {{paramName}} → replaced with param value.

type Locale = 'he-IL' | 'en-US'

const catalog: Record<Locale, Record<string, string>> = {
  'he-IL': {
    'notification.task_assigned.title': 'משימה הוקצתה לך',
    'notification.task_assigned.body': '{{assignerName}} הקצה לך את "{{taskTitle}}"',
    'notification.task_comment.title': 'תגובה חדשה על משימה',
    'notification.task_comment.body': '{{commenterName}} הגיב: {{commentPreview}}',
    'notification.task_status_changed.title': 'סטטוס משימה שונה',
    'notification.task_status_changed.body': '"{{taskTitle}}" עכשיו {{newStatus}}',
    'notification.task_due_soon.title': 'מועד סיום משימה מתקרב',
    'notification.task_due_soon.body': '"{{taskTitle}}" צריך להסתיים ב-{{dueDate}}',
    'notification.task_overdue.title': 'משימה באיחור',
    'notification.task_overdue.body': '"{{taskTitle}}" היה אמור להסתיים ב-{{dueDate}}',
    'notification.task_completed.title': 'משימה הושלמה',
    'notification.task_completed.body': '"{{taskTitle}}" סומנה כהושלמה',
    'notification.invoice_paid.title': 'חשבונית שולמה',
    'notification.invoice_paid.body': 'חשבונית {{invoiceNumber}} על סך {{amount}} שולמה',
    'notification.invoice_overdue.title': 'חשבונית באיחור',
    'notification.invoice_overdue.body': 'חשבונית {{invoiceNumber}} על סך {{amount}} באיחור',
    'notification.invoice_sent.title': 'חשבונית נשלחה',
    'notification.invoice_sent.body': 'חשבונית {{invoiceNumber}} נשלחה אל {{clientName}}',
    'notification.invoice_viewed.title': 'חשבונית נצפתה',
    'notification.invoice_viewed.body': '{{clientName}} צפה בחשבונית {{invoiceNumber}}',
    'notification.invoice_cancelled.title': 'חשבונית בוטלה',
    'notification.invoice_cancelled.body': 'חשבונית {{invoiceNumber}} בוטלה',
    'notification.user_approved.title': 'חשבון אושר',
    'notification.user_approved.body': 'חשבונך אושר. ברוך הבא ל-{{tenantName}}!',
    'notification.user_frozen.title': 'חשבון הושהה',
    'notification.user_frozen.body': 'חשבונך הושהה. צור קשר עם מנהל המערכת.',
    'notification.user_invited.title': 'הוזמנת להצטרף',
    'notification.user_invited.body': '{{inviterName}} הזמין אותך להצטרף ל-{{tenantName}}',
    'notification.user_joined.title': 'חבר חדש הצטרף',
    'notification.user_joined.body': '{{userName}} הצטרף ל-{{tenantName}}',
    'notification.ticket_created.title': 'פנייה נוצרה',
    'notification.ticket_created.body': 'פנייה #{{ticketNumber}}: {{ticketTitle}}',
    'notification.ticket_assigned.title': 'פנייה הוקצתה לך',
    'notification.ticket_assigned.body': 'פנייה #{{ticketNumber}} הוקצתה לך',
    'notification.ticket_replied.title': 'תגובה חדשה על פנייה',
    'notification.ticket_replied.body': '{{replierName}} הגיב לפנייה #{{ticketNumber}}',
    'notification.ticket_resolved.title': 'פנייה נסגרה',
    'notification.ticket_resolved.body': 'פנייה #{{ticketNumber}} נסגרה',
    'notification.ticket_escalated.title': 'פנייה הועברה לדרג גבוה יותר',
    'notification.ticket_escalated.body': 'פנייה #{{ticketNumber}} הועברה לדרג גבוה יותר',
    'notification.expense_submitted.title': 'הוצאה הוגשה',
    'notification.expense_submitted.body': '{{submitterName}} הגיש הוצאה על סך {{amount}}',
    'notification.expense_approved.title': 'הוצאה אושרה',
    'notification.expense_approved.body': 'ההוצאה שלך על סך {{amount}} אושרה',
    'notification.expense_rejected.title': 'הוצאה נדחתה',
    'notification.expense_rejected.body': 'ההוצאה שלך על סך {{amount}} נדחתה. סיבה: {{reason}}',
    'notification.project_created.title': 'פרויקט נוצר',
    'notification.project_created.body': 'פרויקט חדש "{{projectName}}" נוצר',
    'notification.project_member_added.title': 'הוספת לפרויקט',
    'notification.project_member_added.body': 'הוספת לפרויקט "{{projectName}}"',
    'notification.project_deadline_approaching.title': 'מועד פרויקט מתקרב',
    'notification.project_deadline_approaching.body': 'פרויקט "{{projectName}}" צריך להסתיים ב-{{dueDate}}',
    'notification.payment_received.title': 'תשלום התקבל',
    'notification.payment_received.body': 'תשלום של {{amount}} התקבל מ-{{payerName}}',
    'notification.payment_failed.title': 'תשלום נכשל',
    'notification.payment_failed.body': 'תשלום של {{amount}} נכשל. אנא עדכן את אמצעי התשלום.',
    'notification.subscription_expiring.title': 'מנוי עומד לפוג',
    'notification.subscription_expiring.body': 'המנוי שלך יפוג בעוד {{days}} ימים',
    'notification.ai_suggestion_ready.title': 'הצעת AI מוכנה',
    'notification.ai_suggestion_ready.body': 'תובנת AI חדשה זמינה עבור {{entityType}}',
    'notification.system_maintenance.title': 'תחזוקה מתוכננת',
    'notification.system_maintenance.body': 'Zync תהיה בתחזוקה ב-{{date}} בין {{startTime}} ל-{{endTime}}',
    'notification.data_export_ready.title': 'ייצוא נתונים מוכן',
    'notification.data_export_ready.body': 'ייצוא הנתונים שלך מוכן להורדה',
    'notification.mention.title': 'אוזכרת',
    'notification.mention.body': '{{authorName}} אזכר אותך: {{preview}}',
  },
  'en-US': {
    'notification.task_assigned.title': 'Task assigned to you',
    'notification.task_assigned.body': '{{assignerName}} assigned "{{taskTitle}}" to you',
    'notification.task_comment.title': 'New comment on task',
    'notification.task_comment.body': '{{commenterName}} commented: {{commentPreview}}',
    'notification.task_status_changed.title': 'Task status changed',
    'notification.task_status_changed.body': '"{{taskTitle}}" is now {{newStatus}}',
    'notification.task_due_soon.title': 'Task due soon',
    'notification.task_due_soon.body': '"{{taskTitle}}" is due {{dueDate}}',
    'notification.task_overdue.title': 'Task overdue',
    'notification.task_overdue.body': '"{{taskTitle}}" was due {{dueDate}}',
    'notification.task_completed.title': 'Task completed',
    'notification.task_completed.body': '"{{taskTitle}}" was marked complete',
    'notification.invoice_paid.title': 'Invoice paid',
    'notification.invoice_paid.body': 'Invoice {{invoiceNumber}} for {{amount}} has been paid',
    'notification.invoice_overdue.title': 'Invoice overdue',
    'notification.invoice_overdue.body': 'Invoice {{invoiceNumber}} for {{amount}} is overdue',
    'notification.invoice_sent.title': 'Invoice sent',
    'notification.invoice_sent.body': 'Invoice {{invoiceNumber}} was sent to {{clientName}}',
    'notification.invoice_viewed.title': 'Invoice viewed',
    'notification.invoice_viewed.body': '{{clientName}} viewed invoice {{invoiceNumber}}',
    'notification.invoice_cancelled.title': 'Invoice cancelled',
    'notification.invoice_cancelled.body': 'Invoice {{invoiceNumber}} was cancelled',
    'notification.user_approved.title': 'Account approved',
    'notification.user_approved.body': 'Your account has been approved. Welcome to {{tenantName}}!',
    'notification.user_frozen.title': 'Account suspended',
    'notification.user_frozen.body': 'Your account has been suspended. Contact your administrator.',
    'notification.user_invited.title': "You've been invited",
    'notification.user_invited.body': '{{inviterName}} invited you to join {{tenantName}}',
    'notification.user_joined.title': 'New member joined',
    'notification.user_joined.body': '{{userName}} joined {{tenantName}}',
    'notification.ticket_created.title': 'Support ticket created',
    'notification.ticket_created.body': 'Ticket #{{ticketNumber}}: {{ticketTitle}}',
    'notification.ticket_assigned.title': 'Ticket assigned',
    'notification.ticket_assigned.body': 'Ticket #{{ticketNumber}} was assigned to you',
    'notification.ticket_replied.title': 'New reply on ticket',
    'notification.ticket_replied.body': '{{replierName}} replied to ticket #{{ticketNumber}}',
    'notification.ticket_resolved.title': 'Ticket resolved',
    'notification.ticket_resolved.body': 'Ticket #{{ticketNumber}} has been resolved',
    'notification.ticket_escalated.title': 'Ticket escalated',
    'notification.ticket_escalated.body': 'Ticket #{{ticketNumber}} has been escalated',
    'notification.expense_submitted.title': 'Expense submitted',
    'notification.expense_submitted.body': '{{submitterName}} submitted an expense for {{amount}}',
    'notification.expense_approved.title': 'Expense approved',
    'notification.expense_approved.body': 'Your expense of {{amount}} has been approved',
    'notification.expense_rejected.title': 'Expense rejected',
    'notification.expense_rejected.body': 'Your expense of {{amount}} was rejected. Reason: {{reason}}',
    'notification.project_created.title': 'Project created',
    'notification.project_created.body': 'New project "{{projectName}}" was created',
    'notification.project_member_added.title': 'Added to project',
    'notification.project_member_added.body': 'You were added to project "{{projectName}}"',
    'notification.project_deadline_approaching.title': 'Project deadline approaching',
    'notification.project_deadline_approaching.body': 'Project "{{projectName}}" is due {{dueDate}}',
    'notification.payment_received.title': 'Payment received',
    'notification.payment_received.body': 'Payment of {{amount}} received from {{payerName}}',
    'notification.payment_failed.title': 'Payment failed',
    'notification.payment_failed.body': 'Payment of {{amount}} failed. Please update your payment method.',
    'notification.trial_expiring.title': 'Trial expiring soon',
    'notification.trial_expiring.body': 'Your trial expires in {{days}} days. Upgrade to keep access.',
    'notification.subscription_expiring.title': 'Subscription expiring',
    'notification.subscription_expiring.body': 'Your subscription expires in {{days}} days',
    'notification.ai_suggestion_ready.title': 'AI suggestion ready',
    'notification.ai_suggestion_ready.body': 'New AI insight available for {{entityType}}',
    'notification.system_maintenance.title': 'Scheduled maintenance',
    'notification.system_maintenance.body':
      'Zync will be down for maintenance on {{date}} from {{startTime}} to {{endTime}}',
    'notification.data_export_ready.title': 'Data export ready',
    'notification.data_export_ready.body': 'Your data export is ready for download',
    'notification.mention.title': 'You were mentioned',
    'notification.mention.body': '{{authorName}} mentioned you: {{preview}}',
  },
}

/**
 * Interpolates {{paramName}} placeholders in a template string.
 */
function interpolate(template: string, params: Record<string, string>): string {
  return template.replace(/\{\{(\w+)\}\}/g, (_, key) => params[key] ?? `{{${key}}}`)
}

/**
 * Renders notification i18n keys to display strings in the viewer's locale.
 * Falls back to 'he-IL' catalog. If a key is entirely missing, returns the key as-is.
 * body returns null when bodyKey is null.
 */
export function renderNotificationText(
  titleKey: string,
  bodyKey: string | null,
  params: Record<string, string>,
  locale: Locale,
): { title: string; body: string | null } {
  const dict = catalog[locale] ?? catalog['he-IL']

  const titleTemplate =
    candidateKeys(titleKey, 'title')
      .map((key) => dict[key])
      .find((value): value is string => typeof value === 'string')
    ?? titleKey
  const title = interpolate(titleTemplate, params)

  let body: string | null = null
  if (bodyKey !== null) {
    const bodyTemplate =
      candidateKeys(bodyKey, 'body')
        .map((key) => dict[key])
        .find((value): value is string => typeof value === 'string')
      ?? candidateKeys(titleKey, 'body')
        .map((key) => dict[key])
        .find((value): value is string => typeof value === 'string')
      ?? bodyKey
    body = interpolate(bodyTemplate, params)
  }

  return { title, body }
}
