import { baseRequestClient, requestClient } from '#/api/request';

export namespace AuthApi {
  export interface LoginParams {
    account?: string;
    pwd?: string;
    check_code?: string;
    check_key?: string;
  }

  export interface LoginResult {
    isSuccess: boolean;
    code: number;
    error?: string;
    errors?: {
      isFriendlyError?: boolean;
      message?: string;
    };
    errorCode?: string;
    isAuthorized?: boolean;
    accessToken?: string;
    token?: string;
  }

  export interface RefreshTokenResult {
    data: string;
    status: number;
  }

  export interface CaptchaUrlResult {
    w: number;
    h: number;
    len: string;
    key: string;
  }

  export interface SendSmsCodeParams {
    sms_mobile?: string;
    sms_scene?: 'sms_reg';
  }

  export interface SendSmsCodeResult {
    isSuccess: boolean;
  }

  export interface CreateAccountParams {
    sms_scene: 'sms_reg';
    sms_mobile: string;
    sms_check_code: string;
    user: {
      langNameList: [
        {
          name: 'zh-CN';
          value: string;
        },
        {
          name: 'en';
          value: '';
        },
      ];
      password: string;
    };
  }

  export interface UserInfoResult {
    isSuccess: boolean;
    code: number;
    result: {
      accessId: string;
      account: string;
      avatarFileId: string;
      cellPhone: string;
      chineseName: string;
      emailAddress: string;
      englishName: string;
      id: string;
      isActive: boolean;
      langName: string;
      language: string;
      name: string;
      partnerInfoId: string;
    };
    isAuthorized: boolean;
  }
}

/**
 * 登录
 */
export async function loginApi(data: AuthApi.LoginParams) {
  return requestClient.post<AuthApi.LoginResult>(
    '/api/account/doLoginWithCheckCode',
    data,
  );
}

/**
 * 获取用户信息
 */
export async function getUserInfoApi() {
  return requestClient.post<AuthApi.UserInfoResult>('/api/account/curUserInfo');
}

/**
 * 刷新accessToken
 */
export async function refreshTokenApi() {
  return baseRequestClient.post<AuthApi.RefreshTokenResult>('/auth/refresh', {
    withCredentials: true,
  });
}

/**
 * 退出登录
 */
export async function logoutApi() {
  return baseRequestClient.post('/auth/logout', {
    withCredentials: true,
  });
}

/**
 * 获取用户权限码
 */
export async function getAccessCodesApi() {
  return requestClient.get<string[]>('/auth/codes');
}

/**
 * 发送短信验证码
 */
export async function sendSmsCodeApi(data: AuthApi.SendSmsCodeParams) {
  return requestClient.post<AuthApi.SendSmsCodeResult>(
    '/api/system/sendPhoneCode',
    data,
  );
}

/**
 * 创建账户
 */
export async function createAccountApi(data: AuthApi.CreateAccountParams) {
  return requestClient.post('/api/system/registerWithPhoneCode', data);
}
