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

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

  export interface DevLoginParams {
    account: 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>(
    '/api/v1/auth/credential-key',
  );
}

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

/**
 * 开发模式免登录
 */
export async function devLoginApi(data: AuthApi.DevLoginParams) {
  return requestClient.post<AuthApi.LoginResult>(
    '/api/v1/auth/dev-login',
    data,
  );
}

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

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

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