import { translateErrorCode } from './errorMessages.js';

const INFO_TYPES = new Set(['info', 'success', 'warning', 'error']);
const CONFIRM_TYPES = new Set(['info', 'warning', 'danger', 'success']);

function ensureString(value, fallback = '') {
  if (value === null || value === undefined) {
    return fallback;
  }
  if (typeof value === 'string') {
    return value;
  }
  try {
    if (typeof value === 'object') {
      return JSON.stringify(value);
    }
    return String(value);
  } catch (error) {
    return fallback;
  }
}

function sanitizeText(value, fallback = '', maxLength = 500) {
  let text = ensureString(value, fallback).replace(/[\u0000-\u001F]+/g, ' ').trim();
  if (!text) {
    text = fallback;
  }
  if (text.length > maxLength) {
    return `${text.slice(0, maxLength - 1)}…`;
  }
  return text;
}

export function buildInfoConfig({
  title = 'Information',
  message = '',
  details = '',
  detailsHtml = '',
  type = 'info',
  size = 'small',
  closeOnOverlay = true,
  okText = 'OK',
  icon = true,
  t = null, // Übersetzungsfunktion (optional)
} = {}) {
  const safeType = INFO_TYPES.has(type) ? type : 'info';
  
  // Übersetze Standard-Texte, falls t vorhanden
  const defaultTitle = t ? t('messages.info') : 'Information';
  const defaultOkText = t ? t('common.ok') : 'OK';
  
  return {
    isOpen: true,
    title: sanitizeText(title, defaultTitle, 120),
    message: sanitizeText(message, '', 600),
    details: sanitizeText(details, '', 1200),
    // detailsHtml is intentionally not sanitized here to allow HTML tables; callers must ensure safety.
    detailsHtml: typeof detailsHtml === 'string' ? detailsHtml : '',
    type: safeType,
    size,
    closeOnOverlay,
    okText: sanitizeText(okText, defaultOkText, 40),
    icon: typeof icon === 'string' ? sanitizeText(icon, '', 10) : Boolean(icon),
  };
}

export function buildConfirmConfig({
  title = 'Bestätigung',
  message = '',
  details = '',
  type = 'info',
  confirmText = 'OK',
  cancelText = 'Abbrechen',
  showCancel = true,
  resolveCallback = null,
  t = null, // Übersetzungsfunktion (optional)
} = {}) {
  const safeType = CONFIRM_TYPES.has(type) ? type : 'info';
  
  // Übersetze Standard-Texte, falls t vorhanden
  const defaultTitle = t ? t('messages.confirm') : 'Bestätigung';
  const defaultConfirmText = t ? t('common.ok') : 'OK';
  const defaultCancelText = t ? t('common.cancel') : 'Abbrechen';
  
  return {
    isOpen: true,
    title: sanitizeText(title, defaultTitle, 120),
    message: sanitizeText(message, '', 600),
    details: sanitizeText(details, '', 1200),
    type: safeType,
    confirmText: sanitizeText(confirmText, defaultConfirmText, 40),
    cancelText: sanitizeText(cancelText, defaultCancelText, 40),
    showCancel: Boolean(showCancel),
    resolveCallback,
  };
}

export function safeErrorMessage(error, fallback = 'Es ist ein Fehler aufgetreten.', t = null) {
  if (!error) {
    return t ? (t('errors.ERROR_UNKNOWN_ERROR') || fallback) : fallback;
  }

  // Prüfe zuerst auf Fehlercode (neues Format)
  if (error?.response?.data?.code && t) {
    return translateErrorCode(error.response.data.code, error.response.data.params, t);
  }

  // Fallback: Suche nach String-Nachricht
  const candidates = [
    error?.response?.data?.error,
    error?.response?.data?.message,
    error?.response?.data?.errors && Array.isArray(error.response.data.errors)
      ? error.response.data.errors.join(', ')
      : null,
    error?.message,
    error?.statusText,
  ];

  const message = candidates.find((candidate) => typeof candidate === 'string' && candidate.trim().length > 0);
  const finalFallback = t ? (t('errors.ERROR_UNKNOWN_ERROR') || fallback) : fallback;
  return sanitizeText(message, finalFallback, 600);
}

export function sanitizeDetails(details) {
  return sanitizeText(details, '', 1200);
}

export { sanitizeText };
