/**
 * Helper that turns a template key + per-port settings into a final
 * subject line. Centralises the override-resolution + token-substitution
 * pattern so every transactional email sender is one call away from
 * honoring the admin's `email_template_<key>_subject` override.
 *
 * Wire-up (per send site):
 *   const subject = await resolveSubject({
 *     key: 'crm_invite',
 *     portId,
 *     fallback: result.subject,
 *     tokens: { portName, recipientName: data.recipientName, ttlHours: 48 },
 *   });
 *
 * The override is read from `system_settings.email_template_<key>_subject`.
 * If unset / empty / non-string, the `fallback` is returned as-is.
 */

import { loadSubjectOverride, applySubjectTokens } from '@/lib/email/template-overrides';
import type { TemplateKey } from '@/lib/email/template-catalog';

export async function resolveSubject(args: {
  key: TemplateKey;
  /** Optional - when omitted (e.g. system-level emails with no port
   *  context), only the fallback subject is returned. */
  portId?: string | null;
  fallback: string;
  tokens?: Record<string, string | number | undefined>;
}): Promise<string> {
  if (!args.portId) return args.fallback;
  const override = await loadSubjectOverride(args.portId, args.key);
  if (!override) return args.fallback;
  return args.tokens ? applySubjectTokens(override, args.tokens) : override;
}
