import axios, { type AxiosRequestConfig } from 'axios';

const instance = axios.create({
  baseURL: '/api',
  timeout: 10000,
});

instance.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

instance.interceptors.response.use(
  (res) => res.data,
  (err) => {
    const isLoginRequest = err.config?.url === '/auth/login' || err.config?.url === 'auth/login';

    if (err.response?.status === 401 && !isLoginRequest) {
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      localStorage.removeItem('permissions');
      window.location.href = '/login';
    }
    if (err.response?.status === 403) {
      const msg = err.response?.data?.message || '权限不足';
      console.warn('[403]', msg);
    }
    return Promise.reject(err.response?.data || err);
  },
);

const request = <T>(
  method: string,
  url: string,
  data?: unknown,
  config?: AxiosRequestConfig,
): Promise<T> => instance.request({ ...config, method, url, data }) as Promise<T>;

const api = {
  get: <T>(url: string, config?: AxiosRequestConfig): Promise<T> =>
    request<T>('get', url, undefined, config),
  post: <T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> =>
    request<T>('post', url, data, config),
  put: <T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> =>
    request<T>('put', url, data, config),
  patch: <T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T> =>
    request<T>('patch', url, data, config),
  delete: <T>(url: string, config?: AxiosRequestConfig): Promise<T> =>
    request<T>('delete', url, undefined, config),
};

export default api;
