import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';
import { useAuthStore } from '@stores/useAuthStore';
import { useNotificationStore } from '@stores/useNotificationStore';

const API_BASE_URL = import.meta.env.VITE_API_URL || '/api';

export const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Request interceptor - Add auth token
api.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const { token } = useAuthStore.getState();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// Response interceptor - Handle errors and refresh token
api.interceptors.response.use(
  (response) => response,
  async (error: AxiosError) => {
    const originalRequest = error.config;

    // Handle 401 Unauthorized
    if (error.response?.status === 401 && originalRequest) {
      const { logout } = useAuthStore.getState();
      logout();
      window.location.href = '/login';
      return Promise.reject(error);
    }

    // Handle other errors
    const message = getErrorMessage(error);

    // Show notification for server errors
    if (error.response?.status && error.response.status >= 500) {
      useNotificationStore.getState().error('Error del servidor', message);
    }

    return Promise.reject(new Error(message));
  }
);

function getErrorMessage(error: AxiosError): string {
  if (error.response?.data) {
    const data = error.response.data as { error?: string; message?: string };
    return data.error || data.message || 'Error desconocido';
  }

  if (error.code === 'ECONNABORTED') {
    return 'Tiempo de espera agotado';
  }

  if (!error.response) {
    return 'Error de conexión. Verifica tu conexión a internet.';
  }

  return error.message || 'Error desconocido';
}

export default api;
