import type { UserInfo } from '@vben/types';

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

const TENANT_STORAGE_KEY = 'sys-tenant-id';

interface TenantUserProfile {
  account?: string;
  avatar?: string;
  displayName?: string;
  merchantId?: null | number | string;
  packageName?: string;
  permissions?: string[];
  roles?: string[];
  tenantId?: number | string;
  userId?: number | string;
}

function normalizeId(value: null | number | string | undefined) {
  if (value === null || value === undefined) {
    return '';
  }
  return String(value);
}

function mapProfileToUserInfo(profile: TenantUserProfile): UserInfo {
  return {
    avatar: profile.avatar ?? '',
    desc: profile.packageName ?? '',
    homePath: '',
    realName: profile.displayName ?? profile.account ?? '',
    roles: profile.roles ?? [],
    token: '',
    userId: normalizeId(profile.userId),
    username: profile.account ?? '',
  };
}

/**
 * 获取用户信息
 */
export async function getUserInfoApi() {
  const profile = await requestClient.get<TenantUserProfile>('/auth/profile');
  if (profile.tenantId !== null && profile.tenantId !== undefined) {
    localStorage.setItem(TENANT_STORAGE_KEY, String(profile.tenantId));
  }
  return mapProfileToUserInfo(profile);
}
