import { ApiError, type UserRead, usersUsersCurrentUser } from "@/client"

export const SYSTEM_USER_READ: UserRead = {
  id: "system",
  email: "system@tracecat.com",
  role: "admin",
  first_name: "Tracecat",
  last_name: "",
  settings: {},
}

export async function getCurrentUser(): Promise<UserRead | null> {
  try {
    return await usersUsersCurrentUser()
  } catch (error) {
    if (error instanceof ApiError) {
      // Backend throws 401 unauthorized if the user is not logged in
      console.log("User is not logged in")
      return null
    } else {
      console.error("Error fetching current user", error)
      throw error
    }
  }
}

/**
 * Check if user has platform-level admin privileges.
 *
 * Backend platform admin routes are gated by User.is_superuser.
 * For org-level admin checks, use useScopeCheck("org:update").
 */
export function userIsPlatformAdmin(user?: UserRead | null): boolean {
  return user?.is_superuser ?? false
}

export function getDisplayName(
  user: Pick<UserRead, "email" | "first_name" | "last_name">
) {
  if (!user.first_name) {
    return user.email.split("@")[0]
  } else if (user.last_name) {
    return `${user.first_name} ${user.last_name}`
  } else {
    return user.first_name
  }
}

/**
 * User class that wraps UserRead data for authorization checks.
 */
export class User {
  constructor(private user: UserRead) {}

  get id(): string {
    return this.user.id
  }

  get email(): string {
    return this.user.email
  }

  get firstName(): string | null | undefined {
    return this.user.first_name
  }

  get lastName(): string | null | undefined {
    return this.user.last_name
  }

  get settings(): Record<string, unknown> {
    return this.user.settings ?? {}
  }

  get isSuperuser(): boolean {
    return this.user.is_superuser ?? false
  }

  get isActive(): boolean {
    return this.user.is_active ?? false
  }

  get isVerified(): boolean {
    return this.user.is_verified ?? false
  }

  get unwrap(): UserRead {
    return this.user
  }

  /**
   * Returns true if the user has platform-level admin privileges.
   *
   * Backend platform admin routes are gated by User.is_superuser.
   * For org-level admin checks, use useScopeCheck("org:update").
   */
  isPlatformAdmin(): boolean {
    return userIsPlatformAdmin(this.user)
  }

  /**
   * Returns the display name of the user.
   */
  getDisplayName(): string {
    return getDisplayName(this.user)
  }
}

export const SYSTEM_USER = new User(SYSTEM_USER_READ)
