import request from '@/utils/request';
import type { ApiResult } from '@/api';
import type {
  LoginParam,
  LoginResult,
  CaptchaResult,
  SmsCaptchaResult
} from './model';
import {saveStorageByLoginUser, SERVER_API_URL} from "@/utils/server";
import { isUserDisabled } from '@/utils/auth';

/**
 * 账号密码登录
 */
export async function login(data: LoginParam) {
  const res = await request.post<ApiResult<LoginResult>>(
    SERVER_API_URL + '/login',
    data
  );
  if (res.code === 0) {
    if (res.data?.user && res.data?.access_token) {
      if (isUserDisabled(res.data.user)) {
        return Promise.reject(new Error('您的账号已被禁用，请联系管理员'));
      }
      saveStorageByLoginUser(res.data.access_token, res.data.user)
    }
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

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

export async function loginBySms(data: LoginParam) {
  const res = await request.post<ApiResult<LoginResult>>(
    SERVER_API_URL + '/loginBySms',
    data
  );
  if (res.code === 0) {
    if(res.data?.user){
      if (isUserDisabled(res.data.user)) {
        return Promise.reject(new Error('您的账号已被禁用，请联系管理员'));
      }
      saveStorageByLoginUser(`${res.data?.access_token}`, res.data?.user)
    }
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

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