import type { ApiResult } from '@/api';
import { UpdatePasswordParam } from '@/api/layout/model';
import { User } from '@/api/system/user/model';
import request from '@/utils/request';
import { setToken } from '@/utils/token-util';
import type {
  CaptchaResult,
  LoginParam,
  LoginResult,
  SmsCaptchaResult
} from './model';

/**
 * 登录
 */
export async function login(data: LoginParam) {
  const res = await request.post<ApiResult<LoginResult>>('/login', data);
  if (res.data.code === 0) {
    setToken(res.data.data?.access_token, data.remember);
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 获取验证码
 */
export async function getCaptcha() {
  const res = await request.get<ApiResult<CaptchaResult>>('/captcha');
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 发送短信验证码
 */
export async function sendSmsCaptcha(data: LoginParam) {
  const res = await request.post<ApiResult<SmsCaptchaResult>>(
    '/sendSmsCaptcha',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改当前登录的用户密码
 */
export async function updatePassword(
  data: UpdatePasswordParam
): Promise<string> {
  const res = await request.put<ApiResult<unknown>>('/password', data);
  if (res.data.code === 0) {
    return res.data.message ?? '修改成功';
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 注册用户
 */
export async function registerUser(data: User) {
  const res = await request.post<ApiResult<unknown>>('/register', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
