/**
 * Alert i18n Translation Utility
 *
 * Handles translation of alert titles and messages using i18n keys from backend enrichment.
 * Falls back to raw title/message if i18n data is not available.
 */

import { TFunction } from 'i18next';

export interface AlertI18nData {
  title_key?: string;
  title_params?: Record<string, any>;
  message_key?: string;
  message_params?: Record<string, any>;
}



/**
 * Translates alert title only
 *
 * @param alert - Alert object
 * @param t - i18next translation function
 * @returns Translated or fallback title
 */
export function translateAlertTitle(
  alert: {
    i18n?: AlertI18nData;
  },
  t: TFunction
): string {
  if (!alert.i18n?.title_key) {
    return 'Alert';
  }

  try {
    const translated = t(alert.i18n.title_key, alert.i18n.title_params || {});
    return translated !== alert.i18n.title_key ? translated : alert.i18n.title_key;
  } catch (error) {
    console.warn(`Failed to translate alert title with key: ${alert.i18n.title_key}`, error);
    return alert.i18n.title_key;
  }
}

/**
 * Translates alert message only
 *
 * @param alert - Alert object
 * @param t - i18next translation function
 * @returns Translated or fallback message
 */
export function translateAlertMessage(
  alert: {
    i18n?: AlertI18nData;
  },
  t: TFunction
): string {
  if (!alert.i18n?.message_key) {
    return 'No message';
  }

  try {
    const translated = t(alert.i18n.message_key, alert.i18n.message_params || {});
    return translated !== alert.i18n.message_key ? translated : alert.i18n.message_key;
  } catch (error) {
    console.warn(`Failed to translate alert message with key: ${alert.i18n.message_key}`, error);
    return alert.i18n.message_key;
  }
}

/**
 * Checks if alert has i18n data available
 *
 * @param alert - Alert object
 * @returns True if i18n data is present
 */
export function hasI18nData(alert: {
  i18n?: AlertI18nData;
}): boolean {
  return !!(alert.i18n && (alert.i18n.title_key || alert.i18n.message_key));
}
