import {baseRequestClient, requestClient} from '#/api/request';
import {type CredentialKeyMaterial, encryptCredentialPayload,} from '#/utils/credential-encryption';

export namespace AuthApi {
  /** 登录接口参数 */
  export interface LoginParams {
    password?: string;
    username?: string;
  }

  /** 登录接口返回值 */
  export interface LoginResult {
    accessToken: string;
    forceChangePassword?: boolean;
    token: string;
  }

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

/**
 * 获取登录加密公钥
 */
export async function getCredentialKeyApi() {
  return requestClient.get<CredentialKeyMaterial>(
    '/userCenter/auth/credential-key',
  );
}

/**
 * 登录
 */
export async function loginApi(data: AuthApi.LoginParams) {
  const encryptedPayload = await encryptCredentialPayload(
    getCredentialKeyApi,
    data,
  );
  return requestClient.post<AuthApi.LoginResult>(
    '/userCenter/auth/login',
    encryptedPayload,
  );
}

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

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

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