import type {
  AxiosRequestConfig,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from 'axios';
import axios from 'axios';
import Cookies from 'js-cookie';
import { getToken, saveAuthInfo } from './auth';

const instance = axios.create({
  withCredentials: false,
  baseURL: '/',
  validateStatus: (status) => {
    return status >= 200 && status < 500;
  },
});

instance.interceptors.request.use(
  async (config: InternalAxiosRequestConfig) => {
    const token = await getToken();
    if (token) {
      config.headers.setAuthorization(`Bearer ${token}`);
    }
    
    // 从 cookie 中读取语言设置，并添加到请求头
    // 这样后端 API 可以从请求头中获取语言信息
    // 使用 X-Locale 避免与浏览器自动发送的 Accept-Language 冲突
    if (typeof window !== 'undefined') {
      const locale = Cookies.get('locale');
      if (locale) {
        config.headers.set('X-Locale', locale);
      }
    }
    
    return config;
  }
);

instance.interceptors.response.use(
  async (response: AxiosResponse): Promise<AxiosResponse> => {
    if (response.status >= 400 && response.status < 500) {
      if (response.status === 401) {
        // message.error('401：登录过期');
        // saveAuthInfo(null);
        // setTimeout(() => {
        //   window.location.href = '/login';
        // }, 3000);
      } else {
        // message.error(`${response.status}：${response.statusText}`);
      }
    }

    if (response.status >= 500) {
      // notification.error({
      //   message: '网络出现了错误',
      //   description: response.statusText,
      // });
    }

    return response;
  },
  (error) => {
    console.log('error', error);
    if (axios.isCancel(error)) {
      return Promise.resolve('请求取消');
    }

    // notification.error({
    //   message: '网络出现了错误',
    //   description: error,
    // });

    return Promise.reject(error);
  }
);

type ResponseType<T = any> = {
  code: number;
  message: string;
  data: T;
};

async function request<T = any>(
  url: string,
  config?: AxiosRequestConfig
): Promise<ResponseType<T>> {
  let data: any;
  if (config && config?.params) {
    const { params } = config;
    data = Object.fromEntries(
      Object.entries(params).filter(([, value]) => value !== '')
    );
  }
  const response = await instance<ResponseType<T>>(url, {
    ...config,
    params: data,
  });
  return response.data;
}

export default request;
