import type { RequestClientConfig } from '@vben/request';

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

export namespace AuthApi {
  export interface CurrentUserProfile {
    account?: string;
    avatar?: string;
    displayName?: string;
    merchantId?: null | number | string;
    permissions?: string[];
    roles?: string[];
    tenantId?: number | string;
    userId?: number | string;
  }

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

  /** 登录接口返回值 */
  export interface LoginResult {
    accessToken?: string;
    accessTokenExpiresAt?: string;
    isNewUser?: boolean;
    refreshToken?: string;
    refreshTokenExpiresAt?: string;
    user?: CurrentUserProfile;
  }

  export interface RefreshTokenParams {
    refreshToken: string;
  }

  export interface ApiResponse<T> {
    code: number;
    data: T;
    message?: string;
    success: boolean;
  }
}

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

/**
 * 刷新accessToken
 */
export async function refreshTokenApi(
  data: AuthApi.RefreshTokenParams,
  config?: RequestClientConfig,
) {
  return baseRequestClient.post<AuthApi.ApiResponse<AuthApi.LoginResult>>(
    '/auth/refresh',
    data,
    config,
  );
}

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

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