#!/usr/bin/env bash
#
# user-create.sh — Create an Authentik user
#
# Usage: user-create.sh -u <username> -n <name> -e <email> [-p password] [-g group] [-a instance]
#
# Options:
#   -u username   Username (required)
#   -n name       Display name (required)
#   -e email      Email address (required)
#   -p password   Initial password (optional — user gets set-password flow if omitted)
#   -g group      Group name to add user to (optional)
#   -f format     Output format: table (default), json
#   -a instance   Authentik instance name (e.g. usc, mosaic)
#   -h            Show this help
#
# Environment variables (or credentials.json):
#   AUTHENTIK_URL — Authentik instance URL
set -euo pipefail

MOSAIC_HOME="${MOSAIC_HOME:-$HOME/.config/mosaic}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$MOSAIC_HOME/tools/_lib/credentials.sh"

USERNAME="" NAME="" EMAIL="" PASSWORD="" GROUP="" FORMAT="table" AK_INSTANCE=""

while getopts "u:n:e:p:g:f:a:h" opt; do
  case $opt in
    u) USERNAME="$OPTARG" ;;
    n) NAME="$OPTARG" ;;
    e) EMAIL="$OPTARG" ;;
    p) PASSWORD="$OPTARG" ;;
    g) GROUP="$OPTARG" ;;
    f) FORMAT="$OPTARG" ;;
    a) AK_INSTANCE="$OPTARG" ;;
    h) head -19 "$0" | grep "^#" | sed 's/^# \?//'; exit 0 ;;
    *) echo "Usage: $0 -u <username> -n <name> -e <email> [-p password] [-g group] [-a instance]" >&2; exit 1 ;;
  esac
done

if [[ -n "$AK_INSTANCE" ]]; then
  load_credentials "authentik-${AK_INSTANCE}"
else
  load_credentials authentik
fi

if [[ -z "$USERNAME" || -z "$NAME" || -z "$EMAIL" ]]; then
  echo "Error: -u username, -n name, and -e email are required" >&2
  exit 1
fi

TOKEN=$("$SCRIPT_DIR/auth-token.sh" -q ${AK_INSTANCE:+-a "$AK_INSTANCE"})

# Build user payload
payload=$(jq -n \
  --arg username "$USERNAME" \
  --arg name "$NAME" \
  --arg email "$EMAIL" \
  '{username: $username, name: $name, email: $email, is_active: true}')

# Add password if provided
if [[ -n "$PASSWORD" ]]; then
  payload=$(echo "$payload" | jq --arg pw "$PASSWORD" '. + {password: $pw}')
fi

# Add to group if provided
if [[ -n "$GROUP" ]]; then
  # Look up group PK by name
  group_response=$(curl -sk \
    -H "Authorization: Bearer $TOKEN" \
    "${AUTHENTIK_URL}/api/v3/core/groups/?search=${GROUP}")
  group_pk=$(echo "$group_response" | jq -r ".results[] | select(.name == \"$GROUP\") | .pk" | head -1)
  if [[ -n "$group_pk" ]]; then
    payload=$(echo "$payload" | jq --arg gk "$group_pk" '. + {groups: [$gk]}')
  else
    echo "Warning: Group '$GROUP' not found — creating user without group" >&2
  fi
fi

response=$(curl -sk -w "\n%{http_code}" -X POST \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "$payload" \
  "${AUTHENTIK_URL}/api/v3/core/users/")

http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')

if [[ "$http_code" != "201" ]]; then
  echo "Error: Failed to create user (HTTP $http_code)" >&2
  echo "$body" | jq -r '.' 2>/dev/null >&2
  exit 1
fi

if [[ "$FORMAT" == "json" ]]; then
  echo "$body" | jq '.'
else
  echo "User created successfully:"
  echo "$body" | jq -r '"  Username: \(.username)\n  Name:     \(.name)\n  Email:    \(.email)\n  PK:       \(.pk)"'
fi
