/**
 * Internationalization (i18n) Utility
 * Provides multi-language response formatting and translation utilities
 */

const { DEFAULT_LANGUAGE, SUPPORTED_LANGUAGES } = require('../middleware/language');

/**
 * Capitalize first letter of a string
 * @param {string} str - String to capitalize
 * @returns {string} - Capitalized string
 */
const capitalizeFirst = (str) => {
  if (!str) return '';
  return str.charAt(0).toUpperCase() + str.slice(1);
};

/**
 * Get localized field value with fallback to default language
 * @param {Object} obj - Object containing localized fields
 * @param {string} fieldName - Base field name (e.g., 'title', 'description')
 * @param {string} language - Target language code
 * @returns {string} - Localized value or fallback
 */
const getLocalizedField = (obj, fieldName, language = DEFAULT_LANGUAGE) => {
  if (!obj) return '';
  
  const langSuffix = capitalizeFirst(language);
  const localizedField = `${fieldName}${langSuffix}`;
  const defaultField = `${fieldName}${capitalizeFirst(DEFAULT_LANGUAGE)}`;
  
  // Try requested language first
  if (obj[localizedField] && obj[localizedField].trim() !== '') {
    return obj[localizedField];
  }
  
  // Fall back to default language (Chinese)
  if (obj[defaultField] && obj[defaultField].trim() !== '') {
    return obj[defaultField];
  }
  
  // Last resort: return empty string
  return '';
};

/**
 * Format a multi-language object for response
 * @param {Object} obj - Object with multi-language fields
 * @param {Array<string>} fields - Array of field names to localize
 * @param {string} language - Target language code
 * @returns {Object} - Object with localized fields
 */
const formatLocalizedObject = (obj, fields, language = DEFAULT_LANGUAGE) => {
  if (!obj) return null;
  
  const result = { ...obj };
  
  fields.forEach(field => {
    result[field] = getLocalizedField(obj, field, language);
    
    // Remove the language-specific fields
    SUPPORTED_LANGUAGES.forEach(lang => {
      const langField = `${field}${capitalizeFirst(lang)}`;
      delete result[langField];
    });
  });
  
  return result;
};

/**
 * Format service for response with localization
 * @param {Object} service - Service object
 * @param {string} language - Target language code
 * @returns {Object} - Formatted service
 */
const formatServiceResponse = (service, language = DEFAULT_LANGUAGE) => {
  if (!service) return null;
  
  const formatted = {
    id: service.id,
    categoryId: service.categoryId,
    title: getLocalizedField(service, 'title', language),
    description: getLocalizedField(service, 'description', language),
    image: service.image,
    price: service.price,
    status: service.status,
    sortOrder: service.sortOrder,
  };
  
  if (service.category) {
    formatted.category = formatCategoryResponse(service.category, language);
  }
  
  return formatted;
};

/**
 * Format category for response with localization
 * @param {Object} category - Category object
 * @param {string} language - Target language code
 * @returns {Object} - Formatted category
 */
const formatCategoryResponse = (category, language = DEFAULT_LANGUAGE) => {
  if (!category) return null;
  
  return {
    id: category.id,
    key: category.key,
    name: getLocalizedField(category, 'name', language),
    icon: category.icon,
    sortOrder: category.sortOrder,
  };
};

/**
 * Format notification for response with localization
 * @param {Object} notification - Notification object
 * @param {string} language - Target language code
 * @returns {Object} - Formatted notification
 */
const formatNotificationResponse = (notification, language = DEFAULT_LANGUAGE) => {
  if (!notification) return null;
  
  return {
    id: notification.id,
    userId: notification.userId,
    type: notification.type,
    title: getLocalizedField(notification, 'title', language),
    content: getLocalizedField(notification, 'content', language),
    isRead: notification.isRead,
    readAt: notification.readAt,
    createdAt: notification.createdAt,
    updatedAt: notification.updatedAt,
  };
};

/**
 * System messages in multiple languages
 */
const systemMessages = {
  // Success messages
  success: {
    zh: '操作成功',
    en: 'Operation successful',
    pt: 'Operação bem-sucedida',
  },
  created: {
    zh: '创建成功',
    en: 'Created successfully',
    pt: 'Criado com sucesso',
  },
  updated: {
    zh: '更新成功',
    en: 'Updated successfully',
    pt: 'Atualizado com sucesso',
  },
  deleted: {
    zh: '删除成功',
    en: 'Deleted successfully',
    pt: 'Excluído com sucesso',
  },
  
  // Error messages
  notFound: {
    zh: '资源未找到',
    en: 'Resource not found',
    pt: 'Recurso não encontrado',
  },
  unauthorized: {
    zh: '未授权访问',
    en: 'Unauthorized access',
    pt: 'Acesso não autorizado',
  },
  forbidden: {
    zh: '禁止访问',
    en: 'Access forbidden',
    pt: 'Acesso proibido',
  },
  validationError: {
    zh: '验证错误',
    en: 'Validation error',
    pt: 'Erro de validação',
  },
  serverError: {
    zh: '服务器错误',
    en: 'Server error',
    pt: 'Erro do servidor',
  },
  
  // Appointment messages
  appointmentCreated: {
    zh: '预约创建成功',
    en: 'Appointment created successfully',
    pt: 'Agendamento criado com sucesso',
  },
  appointmentCancelled: {
    zh: '预约已取消',
    en: 'Appointment cancelled',
    pt: 'Agendamento cancelado',
  },
  
  // Notification messages
  notificationRead: {
    zh: '通知已标记为已读',
    en: 'Notification marked as read',
    pt: 'Notificação marcada como lida',
  },
  allNotificationsRead: {
    zh: '所有通知已标记为已读',
    en: 'All notifications marked as read',
    pt: 'Todas as notificações marcadas como lidas',
  },
};

/**
 * Get system message in specified language
 * @param {string} key - Message key
 * @param {string} language - Target language code
 * @returns {string} - Localized message
 */
const getSystemMessage = (key, language = DEFAULT_LANGUAGE) => {
  const message = systemMessages[key];
  if (!message) return key;
  
  return message[language] || message[DEFAULT_LANGUAGE] || key;
};

/**
 * Create localized response
 * @param {boolean} success - Whether operation was successful
 * @param {Object} data - Response data
 * @param {string} messageKey - Message key for localization
 * @param {string} language - Target language code
 * @returns {Object} - Formatted response
 */
const createLocalizedResponse = (success, data, messageKey, language = DEFAULT_LANGUAGE) => {
  return {
    success,
    message: getSystemMessage(messageKey, language),
    data,
  };
};

module.exports = {
  capitalizeFirst,
  getLocalizedField,
  formatLocalizedObject,
  formatServiceResponse,
  formatCategoryResponse,
  formatNotificationResponse,
  getSystemMessage,
  createLocalizedResponse,
  systemMessages,
};
