# User management commands for the NATS admin bus.
#
# Sends structured requests to the `admin.users` NATS subject.  The server-side
# subscriber must handle this subject with access to the auth repository.
#
# Request envelope: { "op": "list" | "get" | "disable" | "reset_sessions", ...fields }
# Response envelope: { "ok": bool, "data": any, "error": string | null }

use ./common.nu [build-admin-subject, nats-admin-request]

# Internal: send a users operation and unwrap the data payload.
def users-request [payload: record, --url: string = "", --creds: string = ""] {
    let subject = build-admin-subject "admin.users"
    let json_payload = $payload | to json --raw

    let response = nats-admin-request $subject $json_payload --url $url --creds $creds --timeout "15s"
        | from json

    if not ($response.ok? | default false) {
        let msg = $response.error? | default "unknown error from admin.users"
        error make { msg: $"admin.users error: ($msg)" }
    }

    $response.data? | default {}
}

# List all registered users.
#
# Returns a table with: id, email, display_name, roles, created_at, is_active
#
# Examples:
#   nats-admin users list
#   nats-admin users list | where { |u| "admin" in $u.roles }
#   nats-admin users list | length   # total user count
export def "nats-admin users list" [
    --url:   string = ""
    --creds: string = ""
] {
    users-request { op: "list" } --url $url --creds $creds
}

# Get a single user by email address.
#
# Examples:
#   nats-admin users get admin@example.com
export def "nats-admin users get" [
    email: string  # User email address
    --url:   string = ""
    --creds: string = ""
] {
    users-request { op: "get", email: $email } --url $url --creds $creds
}

# Disable a user account (sets is_active = false, does not delete).
#
# Examples:
#   nats-admin users disable spammer@example.com
export def "nats-admin users disable" [
    email: string
    --url:   string = ""
    --creds: string = ""
] {
    users-request { op: "disable", email: $email } --url $url --creds $creds
    print $"User ($email) disabled."
}

# Invalidate all active sessions for a user, forcing re-login.
#
# Examples:
#   nats-admin users reset-sessions user@example.com
export def "nats-admin users reset-sessions" [
    email: string
    --url:   string = ""
    --creds: string = ""
] {
    users-request { op: "reset_sessions", email: $email } --url $url --creds $creds
    print $"Sessions reset for ($email)."
}
