import { ManagementClient } from "auth0"

// Create a singleton instance or allow injection
let managementClient: ManagementClient | null = null

export function getManagementClient(): ManagementClient {
  managementClient ||= new ManagementClient({
    domain: process.env.AUTH0_ISSUER_BASE_URL ?? "",
    clientId: process.env.AUTH0_MANAGEMENT_CLIENT_ID ?? "",
    clientSecret: process.env.AUTH0_MANAGEMENT_CLIENT_SECRET ?? "",
  })
  return managementClient
}

// For testing purposes
export function setManagementClient(client: ManagementClient | null) {
  managementClient = client
}

export async function userNickname(userId: string): Promise<string | null> {
  const m = getManagementClient()
  try {
    const user = await m.users.get({ id: userId, fields: "nickname" })
    return user.data?.nickname ?? null
  } catch (error) {
    console.log("Error getting user nickname:", error)
    return null
  }
}
