#!/usr/bin/env bash
set -euo pipefail

BASE_URL=${BASE_URL:-http://localhost:8080}
USERNAME=${USERNAME:-admin}
PASSWORD=${PASSWORD:-Pass@123}
LOG_FILE=${LOG_FILE:-}

pretty_json_or_raw() {
  local input="$1"
  if jq -e . >/dev/null 2>&1 <<<"$input"; then
    jq . <<<"$input"
  else
    printf '%s\n' "$input"
  fi
}

timestamp() {
  date '+%Y-%m-%dT%H:%M:%S%z'
}

log() {
  local message="$1"
  echo "$message" >&2
  if [[ -n "$LOG_FILE" ]]; then
    printf '[%s] %s\n' "$(timestamp)" "$message" >>"$LOG_FILE"
  fi
}

log_block() {
  local heading="$1"
  local body="$2"
  if [[ -n "$LOG_FILE" ]]; then
    {
      printf '[%s] %s\n' "$(timestamp)" "$heading"
      pretty_json_or_raw "$body"
    } >>"$LOG_FILE"
  fi
}

usage() {
  cat <<USAGE
Usage: $(basename "$0") [--url <baseUrl>] [--user <username>] [--pass <password>] [--log <file>]
You can also set environment variables: BASE_URL, USERNAME, PASSWORD, LOG_FILE.
USAGE
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --url)
      BASE_URL=$2
      shift 2
      ;;
    --user)
      USERNAME=$2
      shift 2
      ;;
    --pass)
      PASSWORD=$2
      shift 2
      ;;
    --log)
      LOG_FILE=$2
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage
      exit 1
      ;;
  esac
done

if [[ -n "$LOG_FILE" ]]; then
  mkdir -p "$(dirname "$LOG_FILE")"
  touch "$LOG_FILE"
  log "Logging enabled: $LOG_FILE"
fi

for tool in curl jq; do
  if ! command -v "$tool" >/dev/null 2>&1; then
    log "Error: $tool is required but not installed."
    exit 1
  fi
done

log "Logging in as $USERNAME against $BASE_URL..."
LOGIN_RESPONSE=$(curl -sS -X POST "$BASE_URL/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d "{\"username\":\"$USERNAME\",\"password\":\"$PASSWORD\"}")

if ! ACCESS_TOKEN=$(printf '%s' "$LOGIN_RESPONSE" | jq -er '.accessToken'); then
  log "Login failed. Response: $LOGIN_RESPONSE"
  exit 1
fi

EXPIRES_IN=$(printf '%s' "$LOGIN_RESPONSE" | jq -r '.expiresIn // "unknown"')
ROLES=$(printf '%s' "$LOGIN_RESPONSE" | jq -r '.roles | join(", ")')

log "Token acquired (expires in ${EXPIRES_IN}s) with roles: ${ROLES}"

SANITIZED_LOGIN_RESPONSE=$(printf '%s' "$LOGIN_RESPONSE" | jq '.accessToken="***redacted***"')
log_block "Login response" "$SANITIZED_LOGIN_RESPONSE"

log "Calling /api/as400/databases..."
DB_RESPONSE=$(curl -sS "$BASE_URL/api/v1/as400/databases" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Accept: application/json")

log_block "Databases response" "$DB_RESPONSE"
pretty_json_or_raw "$DB_RESPONSE"
