import { jest, describe, it, expect, beforeEach, afterEach } from "@jest/globals"
import { userNickname, setManagementClient } from "./auth0-mgmt"

describe("userNickname", () => {
  let mockUsersGet: jest.MockedFunction<any>
  let mockManagementClient: any

  beforeEach(() => {
    // Create mock for users.get
    mockUsersGet = jest.fn()

    // Create mock management client
    mockManagementClient = {
      users: {
        get: mockUsersGet,
      },
    }

    // Inject the mock
    setManagementClient(mockManagementClient)
  })

  afterEach(() => {
    // Clean up
    setManagementClient(null)
  })

  it("should return nickname when user is found", async () => {
    mockUsersGet.mockResolvedValue({ data: { nickname: "cool-user" } })

    const nickname = await userNickname("user-123")

    expect(nickname).toBe("cool-user")
    expect(mockUsersGet).toHaveBeenCalledWith({ id: "user-123", fields: "nickname" })
  })

  it("should return null when nickname is missing", async () => {
    mockUsersGet.mockResolvedValue({ data: {} })

    const nickname = await userNickname("user-456")

    expect(nickname).toBeNull()
    expect(mockUsersGet).toHaveBeenCalledWith({ id: "user-456", fields: "nickname" })
  })

  it("should return null and log error on exception", async () => {
    const error = new Error("API error")
    mockUsersGet.mockRejectedValue(error)

    const consoleSpy = jest.spyOn(console, "log").mockImplementation(() => {})

    const nickname = await userNickname("user-789")

    expect(nickname).toBeNull()
    expect(consoleSpy).toHaveBeenCalledWith("Error getting user nickname:", error)
    expect(mockUsersGet).toHaveBeenCalledWith({ id: "user-789", fields: "nickname" })

    consoleSpy.mockRestore()
  })
})
