/**
 * ValidationAdapter - Transforms HTML Editor validation data to ErrorInfoNote format
 *
 * This adapter converts validation results from the HTML Editor's validation system
 * into the format expected by the existing ErrorInfoNote component.
 */

// Validation source constants
const VALIDATION_SOURCES = {
  LIQUID: 'liquid-validator',
  HTMLHINT: 'htmlhint',
  CSS_VALIDATOR: 'css-validator',
  CUSTOM: 'custom',
  SECURITY: 'security',
  SANITIZER: 'sanitizer',
  EMAIL_SPECIFIC: 'email-specific',
  INAPP_SPECIFIC: 'inapp-specific',
  EMAIL_COMPATIBILITY: 'email-compatibility',
  MOBILE_OPTIMIZATION: 'mobile-optimization',
};

/**
 * Transform validation results to ErrorInfoNote format
 * @param {Object} validation - Validation results from useValidation hook
 * @param {string} variant - Editor variant ('email' or 'inapp')
 * @returns {Object} ErrorInfoNote compatible format
 */
export const transformValidationToErrorInfo = (validation, variant = 'email') => {
  if (!validation || validation.isValidating) {
    return { errorMessages: { LIQUID_ERROR_MSG: [], STANDARD_ERROR_MSG: [] } };
  }

  if (typeof validation.getAllIssues !== 'function') {
    console.warn('[validationAdapter] validation.getAllIssues is not a function:', validation);
    return { errorMessages: { LIQUID_ERROR_MSG: [], STANDARD_ERROR_MSG: [] } };
  }

  const allIssues = validation.getAllIssues();
  // Safety check: ensure allIssues is an array
  if (!Array.isArray(allIssues)) {
    console.warn('[validationAdapter] validation.getAllIssues() did not return an array:', allIssues);
    return { errorMessages: { LIQUID_ERROR_MSG: [], STANDARD_ERROR_MSG: [] } };
  }

  // Separate liquid and standard errors
  const liquidErrors = allIssues.filter((issue) => issue.source === VALIDATION_SOURCES.LIQUID
    || issue.rule?.includes('liquid')
    || issue.message?.toLowerCase().includes('liquid'));

  const standardErrors = allIssues.filter((issue) => issue.source !== VALIDATION_SOURCES.LIQUID
    && !issue.rule?.includes('liquid')
    && !issue.message?.toLowerCase().includes('liquid'));

  // Format errors for ErrorInfoNote
  const formatErrors = (errors) => errors.map((error) => {
    let {message} = error;

    // Add line/column info if available
    if (error.line) {
      message += ` Line ${error.line}`;
      if (error.column) {
        message += `, Char ${error.column}`;
      }
      message += '.';
    }

    // Add rule info if available
    if (error.rule) {
      message += ` • ${error.rule}`;
    }

    return message;
  });

  // Handle InApp variant with platform-specific errors (if needed in future)
  if (variant === 'inapp') {
    // For now, treat as generic errors
    // Could be extended to support Android/iOS specific validation
    return {
      errorMessages: {
        LIQUID_ERROR_MSG: formatErrors(liquidErrors),
        STANDARD_ERROR_MSG: formatErrors(standardErrors),
      },
    };
  }

  // Email variant - generic errors
  return {
    errorMessages: {
      LIQUID_ERROR_MSG: formatErrors(liquidErrors),
      STANDARD_ERROR_MSG: formatErrors(standardErrors),
    },
  };
};

/**
 * Check if there are any validation errors to display
 * @param {Object} validation - Validation results
 * @returns {boolean} True if there are errors to show
 */
export const hasValidationErrors = (validation) => {
  if (!validation || validation.isValidating) {
    return false;
  }

  if (typeof validation.getAllIssues !== 'function') {
    console.warn('[validationAdapter] validation.getAllIssues is not a function:', validation);
    return false;
  }

  const allIssues = validation.getAllIssues();
  // Safety check: ensure allIssues is an array
  if (!Array.isArray(allIssues)) {
    console.warn('[validationAdapter] validation.getAllIssues() did not return an array:', allIssues);
    return false;
  }

  return allIssues.length > 0;
};

/**
 * Get validation summary for display
 * @param {Object} validation - Validation results
 * @returns {Object} Summary with counts
 */
export const getValidationSummary = (validation) => {
  if (!validation) {
    return { totalErrors: 0, totalWarnings: 0, hasLiquidErrors: false };
  }

  if (typeof validation.getAllIssues !== 'function') {
    console.warn('[validationAdapter] validation.getAllIssues is not a function:', validation);
    return { totalErrors: 0, totalWarnings: 0, hasLiquidErrors: false };
  }

  const allIssues = validation.getAllIssues();
  // Safety check: ensure allIssues is an array
  if (!Array.isArray(allIssues)) {
    console.warn('[validationAdapter] validation.getAllIssues() did not return an array:', allIssues);
    return { totalErrors: 0, totalWarnings: 0, hasLiquidErrors: false };
  }

  const errors = allIssues.filter((issue) => issue.severity === 'error');
  const warnings = allIssues.filter((issue) => issue.severity === 'warning');
  const liquidErrors = allIssues.filter((issue) => issue.source === VALIDATION_SOURCES.LIQUID
    || issue.rule?.includes('liquid')
    || issue.message?.toLowerCase().includes('liquid'));

  return {
    totalErrors: errors.length,
    totalWarnings: warnings.length,
    hasLiquidErrors: liquidErrors.length > 0,
    totalIssues: allIssues.length,
  };
};
