import axiosInstance from './axiosConfig';
import { loginSuccess } from '../utils/jwt';


/**
 * 获取验证码
 * @returns {Promise<any>} 返回一个包含验证码信息的Promise对象
 */
export const getCaptcha = async () => {
    try {
        const response = await axiosInstance.get('/captcha');
        return response.data;
    } catch (error) {
        throw error;
    }
};

/**
 * 用户登录
 * @param {string} username - 用户名
 * @param {string} password - 密码
 * @param {string} token - 验证码token
 * @param {string} captcha - 用户输入的验证码
 * @returns {Promise<any>} 返回一个包含登录结果信息的Promise对象
 */
export const userLogin = async (username, password, token, captcha) => {
    try {
        const response = await axiosInstance.post('/user/login', {
            username,
            password,
            token,
            captcha
        });
        
        if (response.data.access_token) {
            loginSuccess(response.data.access_token, username);
        }
        
        return response.data;
    } catch (error) {
        throw error;
    }
};

/**
 * 用户注册
 * @param {string} qq_code - QQ号
 * @param {string} password - 密码
 * @param {string} token - 验证码token
 * @param {string} captcha - 用户输入的验证码
 * @returns {Promise<any>} 返回一个包含注册结果信息的Promise对象
 */
export const userRegister = async (qq_code, password, token, captcha) => {
    try {
        const response = await axiosInstance.post('/user/register', {
            qq_code,
            password,
            token,
            captcha
        });
        return response.data;
    } catch (error) {
        throw error;
    }
};

/**
 * 管理员修改用户权限
 * @param {string} uuid - 用户uuid
 * @param {string} privilege - 新权限
 * @returns {Promise<void>} 无返回值，成功即为修改成功
 */
export const adminChangeUserPrivilege = async (uuid, privilege) => {
  try {
    await axiosInstance.put('/admin/change_user_privilege', {
      uuid,
      privilege
    });
  } catch (error) {
    throw error;
  }
}

