/**
 * Centralized error handling utilities for WooNooW Admin SPA
 * 
 * Guidelines:
 * - Use toast notifications for ACTION errors (mutations: create, update, delete)
 * - Use error cards/messages for PAGE LOAD errors (queries: fetch data)
 * - Never show technical details (API 500, stack traces) to users
 * - Always provide actionable, user-friendly messages
 * - All user-facing strings are translatable
 */

import { toast } from 'sonner';
import { __ } from './i18n';

/**
 * Extract user-friendly error message from API error response
 */
export function getErrorMessage(error: any): { title: string; description?: string } {
  // Extract error details from response
  const errorMessage = error?.response?.data?.message || error?.message || '';
  const errorCode = error?.response?.data?.error || '';
  const fieldErrors = error?.response?.data?.fields || [];
  
  // Remove technical prefixes like "API 500:"
  const cleanMessage = errorMessage.replace(/^API\s+\d+:\s*/i, '');
  
  // Map error codes to user-friendly messages (all translatable)
  const friendlyMessages: Record<string, string> = {
    // Order errors
    'no_items': __('Please add at least one product to the order'),
    'create_failed': __('Failed to create order. Please check all required fields.'),
    'update_failed': __('Failed to update order. Please check all fields.'),
    'validation_failed': __('Please complete all required fields'),
    'not_found': __('The requested item was not found'),
    'forbidden': __('You do not have permission to perform this action'),
    
    // Generic errors
    'validation_error': __('Please check your input and try again'),
    'server_error': __('Something went wrong. Please try again later.'),
  };
  
  const title = friendlyMessages[errorCode] || __('An error occurred');
  
  // Build description from field errors or clean message
  let description: string | undefined;
  
  if (fieldErrors.length > 0) {
    // Show specific field errors as a bulleted list
    description = fieldErrors.map((err: string) => `• ${err}`).join('\n');
  } else if ((errorCode === 'create_failed' || errorCode === 'update_failed' || errorCode === 'validation_failed') && cleanMessage) {
    description = cleanMessage;
  }
  
  return { title, description };
}

/**
 * Show error toast for mutation/action errors
 * Use this for: create, update, delete, form submissions
 */
export function showErrorToast(error: any, customMessage?: string) {
  console.error('Action error:', error);
  
  const { title, description } = getErrorMessage(error);
  
  toast.error(customMessage || title, {
    description,
    duration: 6000, // Longer for errors
  });
}

/**
 * Show success toast for successful actions
 */
export function showSuccessToast(message: string, description?: string) {
  toast.success(message, {
    description,
    duration: 4000,
  });
}

/**
 * Get error message for page load errors (queries)
 * Use this for: rendering error states in components
 */
export function getPageLoadErrorMessage(error: any): string {
  const { title } = getErrorMessage(error);
  return title;
}
