import axios, { AxiosError } from 'axios';
import { i18n } from '@lingui/core';
import { t } from '@lingui/macro';

export interface ErrorResponse {
  message: string;
  errors?: Record<string, string[]>;
  status?: number;
}

export function extractErrorMessage(error: unknown): string {
  if (!axios.isAxiosError(error)) {
    if (error instanceof Error) {
      return error.message;
    }
    return i18n._(t`Ein unerwarteter Fehler ist aufgetreten`);
  }

  const axiosError = error as AxiosError<ErrorResponse>;

  if (!axiosError.response) {
    if (axiosError.message === 'Network Error') {
      return i18n._(t`Netzwerkfehler. Bitte überprüfen Sie Ihre Internetverbindung.`);
    }
    return axiosError.message || i18n._(t`Verbindung zum Server fehlgeschlagen`);
  }

  const { status, data } = axiosError.response;

  switch (status) {
    case 401:
      return i18n._(t`Nicht autorisiert. Bitte melden Sie sich erneut an.`);
    case 403:
      return i18n._(t`Sie haben keine Berechtigung für diese Aktion.`);
    case 404:
      return i18n._(t`Die angeforderte Ressource wurde nicht gefunden.`);
    case 422:
      if (data?.errors) {
        const errorMessages = Object.values(data.errors).flat();
        return errorMessages.join(', ');
      }
      return data?.message || i18n._(t`Validierung fehlgeschlagen`);
    case 429:
      return i18n._(t`Zu viele Anfragen. Bitte versuchen Sie es später erneut.`);
    case 500:
    case 502:
    case 503:
    case 504:
      return i18n._(t`Serverfehler. Bitte versuchen Sie es später erneut.`);
    default:
      return data?.message || i18n._(t`Fehler: ${status}`);
  }
}

export function extractValidationErrors(error: unknown): Record<string, string> {
  if (!axios.isAxiosError(error)) {
    return {};
  }

  const axiosError = error as AxiosError<ErrorResponse>;
  const errors = axiosError.response?.data?.errors;

  if (!errors) {
    return {};
  }

  const fieldErrors: Record<string, string> = {};
  Object.entries(errors).forEach(([field, messages]) => {
    fieldErrors[field] = messages.join(', ');
  });

  return fieldErrors;
}

export function isNetworkError(error: unknown): boolean {
  return axios.isAxiosError(error) && !error.response;
}

export function isValidationError(error: unknown): boolean {
  return axios.isAxiosError(error) && error.response?.status === 422;
}

export function isAuthError(error: unknown): boolean {
  if (!axios.isAxiosError(error)) {
    return false;
  }
  const status = error.response?.status;
  return status === 401 || status === 403;
}

export function isServerError(error: unknown): boolean {
  if (!axios.isAxiosError(error)) {
    return false;
  }
  const status = error.response?.status;
  return status !== undefined && status >= 500 && status < 600;
}

export function logError(context: string, error: unknown): void {
  console.error(`[${context}]`, error);
}

export function handleApiError(context: string, error: unknown): string {
  logError(context, error);
  return extractErrorMessage(error);
}
