/**
 * Helper function to convert raw API error strings into user-friendly messages
 * Used throughout the app to provide contextual error guidance
 */

export interface ErrorMessageResult {
  title: string;
  description: string;
  action?: string;
  actionUrl?: string;
}

export function getAnalysisErrorMessage(error: string): ErrorMessageResult {
  const errorLower = error.toLowerCase();

  // GSC quota/rate limit errors
  if (
    errorLower.includes('quota') ||
    errorLower.includes('rate limit') ||
    errorLower.includes('429')
  ) {
    return {
      title: 'Google Search Console Limit Reached',
      description:
        'Your daily GSC quota has been reached. Analysis will automatically retry tomorrow, or you can try again in 24 hours.',
    };
  }

  // GSC authentication/connection errors
  if (
    (errorLower.includes('gsc') || errorLower.includes('search console')) &&
    (errorLower.includes('auth') ||
      errorLower.includes('token') ||
      errorLower.includes('401') ||
      errorLower.includes('403'))
  ) {
    return {
      title: 'GSC Connection Lost',
      description:
        'Your Google Search Console connection has expired. Reconnect in Settings to resume analysis.',
      action: 'Reconnect',
      actionUrl: 'settings',
    };
  }

  // WordPress connection/plugin errors
  if (
    (errorLower.includes('wp') ||
      errorLower.includes('wordpress') ||
      errorLower.includes('plugin')) &&
    (errorLower.includes('connection') ||
      errorLower.includes('timeout') ||
      errorLower.includes('500') ||
      errorLower.includes('unreachable'))
  ) {
    return {
      title: 'WordPress Connection Issue',
      description:
        'Unable to reach your WordPress site. Check that the RankWiz plugin is active and properly configured.',
      action: 'Check Connection',
      actionUrl: 'settings',
    };
  }

  // Network/timeout errors
  if (
    errorLower.includes('timeout') ||
    errorLower.includes('network') ||
    errorLower.includes('econnrefused')
  ) {
    return {
      title: 'Network Error',
      description:
        'Unable to connect to required services. Please check your internet connection and try again.',
    };
  }

  // Default error message
  return {
    title: 'Analysis Error',
    description:
      'Something unexpected went wrong. Our team has been notified. You can try running the analysis again.',
    action: 'Retry Analysis',
  };
}

/**
 * Converts actionUrl string to a full route path
 */
export function getErrorActionUrl(actionUrl?: string, siteId?: number): string | undefined {
  if (!actionUrl) return undefined;

  if (actionUrl === 'settings') {
    return siteId ? `/sites/${siteId}/settings/connections` : '/settings';
  }

  return actionUrl;
}
