import type { NotificationTemplateRecord } from '../types';

const TOKEN_PATTERN = /\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g;

function resolveTokenValue(payload: Record<string, unknown>, token: string): string {
  const value = token.split('.').reduce<unknown>((current, part) => {
    if (!current || typeof current !== 'object') {
      return undefined;
    }

    return (current as Record<string, unknown>)[part];
  }, payload);

  if (value === null || value === undefined || value === '') {
    return '-';
  }

  if (typeof value === 'string') {
    return value;
  }

  if (typeof value === 'number' || typeof value === 'boolean') {
    return String(value);
  }

  return '-';
}

function renderString(template: string | null, payload: Record<string, unknown>): string | null {
  if (!template) {
    return null;
  }

  return template.replace(TOKEN_PATTERN, (_match, token: string) => resolveTokenValue(payload, token));
}

export function renderNotificationTemplate(
  template: Pick<NotificationTemplateRecord, 'titleTemplate' | 'bodyTemplate' | 'linkTemplate'>,
  payload: Record<string, unknown>
) {
  return {
    title: renderString(template.titleTemplate, payload) ?? '-',
    body: renderString(template.bodyTemplate, payload) ?? '-',
    linkUrl: renderString(template.linkTemplate, payload)
  };
}
