import axios from "axios";

// 创建一个单独的 axios 实例用于认证请求（不需要 token）
const authApi = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 60000,
  headers: {
    "Content-Type": "application/json",
  },
});

// 响应拦截器
authApi.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    console.error("认证请求失败", error);
    return Promise.reject(error);
  }
);

/**
 * 用户登录
 * @param {string} username - 用户名
 * @param {string} password - 密码
 * @param {string} corpId - 企业ID（可选）
 * @returns {Promise}
 */
export async function login({ username, password, corpId }) {
  try {
    const result = await authApi.post("/auth/login", {
      username,
      password,
      corpId,
    });
    return result;
  } catch (error) {
    return {
      success: false,
      message: error.message || "登录失败，请稍后再试",
    };
  }
}

/**
 * 刷新 Token
 * @param {string} refreshToken - 刷新令牌
 * @returns {Promise}
 */
export async function refreshToken(refreshToken) {
  try {
    const result = await authApi.post("/auth/refresh", {
      refreshToken,
    });
    return result;
  } catch (error) {
    return {
      success: false,
      message: error.message || "Token 刷新失败",
    };
  }
}

/**
 * 获取当前用户信息
 * @param {string} accessToken - 访问令牌
 * @returns {Promise}
 */
export async function getCurrentUser(accessToken) {
  try {
    const result = await authApi.get("/auth/current", {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
    return result;
  } catch (error) {
    return {
      success: false,
      message: error.message || "获取用户信息失败",
    };
  }
}

/**
 * 退出登录
 * @param {string} accessToken - 访问令牌
 * @returns {Promise}
 */
export async function logout(accessToken) {
  try {
    const result = await authApi.post(
      "/auth/logout",
      {},
      {
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      }
    );
    return result;
  } catch (error) {
    return {
      success: false,
      message: error.message || "退出登录失败",
    };
  }
}

