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

AUTH_URL="${AUTH_URL:-https://auth.kullervokapital.com}"
ADMIN_KEY="${OWALISAATTORI_ADMIN_KEY:-${OWALUATOR_ADMIN_KEY:-}}"

if [[ "${OG_ADMIN_SILENCE_DEPRECATION:-0}" != "1" ]]; then
  echo "[DEPRECATED] Tämä skripti käyttää legacy X-Admin-Key -kutsuja." >&2
  echo "[DEPRECATED] Suositus: käytä OG-Admin Control Planea käyttäjä- ja roolihallintaan." >&2
fi

if [[ -z "${ADMIN_KEY}" ]]; then
  echo "Puuttuva admin-avain"
  echo "Aseta: export OWALISAATTORI_ADMIN_KEY='...'"
  echo "Tai yhteensopivasti: export OWALUATOR_ADMIN_KEY='...'"
  exit 1
fi

usage() {
  cat <<EOF
Käyttö:
  $(basename "$0") list
  $(basename "$0") add <email> [password] [role]
  $(basename "$0") disable <id|email>
  $(basename "$0") enable <id|email>
  $(basename "$0") remove <id|email>
  $(basename "$0") reset-password <id|email> [new_password]

Ympäristömuuttujat:
  AUTH_URL (oletus: ${AUTH_URL})
  OWALISAATTORI_ADMIN_KEY (ensisijainen)
  OWALUATOR_ADMIN_KEY (fallback)
EOF
}

rand_password() {
  python3 - <<'PY'
import secrets
alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%*+?"
print("".join(secrets.choice(alphabet) for _ in range(18)))
PY
}

api_call() {
  local method="$1"
  local path="$2"
  local payload="${3:-}"
  local tmp_body
  tmp_body="$(mktemp)"
  local http_code=""

  if [[ -n "${payload}" ]]; then
    http_code="$(curl -sS --connect-timeout 10 --max-time 30 -o "${tmp_body}" -w "%{http_code}" -X "${method}" "${AUTH_URL}${path}" \
      -H "Content-Type: application/json" \
      -H "X-Admin-Key: ${ADMIN_KEY}" \
      -d "${payload}" || true)"
  else
    http_code="$(curl -sS --connect-timeout 10 --max-time 30 -o "${tmp_body}" -w "%{http_code}" -X "${method}" "${AUTH_URL}${path}" \
      -H "X-Admin-Key: ${ADMIN_KEY}" || true)"
  fi

  if [[ ! "${http_code}" =~ ^2[0-9][0-9]$ ]]; then
    echo "API-kutsu epäonnistui: ${method} ${AUTH_URL}${path} (HTTP ${http_code:-000})" >&2
    echo "Vastaus:" >&2
    cat "${tmp_body}" >&2 || true
    rm -f "${tmp_body}"
    exit 1
  fi

  cat "${tmp_body}"
  rm -f "${tmp_body}"
}

assert_json() {
  local payload="$1"
  python3 - "${payload}" <<'PY'
import json,sys
payload = sys.argv[1]
try:
    json.loads(payload)
except Exception as e:
    print(f"Virhe: palvelin ei palauttanut validia JSON-vastausta ({e})", file=sys.stderr)
    sys.exit(1)
PY
}

users_json() {
  local body
  body="$(api_call "GET" "/admin/users")"
  if [[ -z "${body}" ]]; then
    echo "Virhe: tyhjä vastaus endpointista ${AUTH_URL}/admin/users" >&2
    exit 1
  fi
  if ! assert_json "${body}" >/dev/null; then
    echo "Raakavastaus endpointista ${AUTH_URL}/admin/users:" >&2
    printf "%s\n" "${body}" >&2
    exit 1
  fi
  printf "%s" "${body}"
}

resolve_user_id() {
  local ident="$1"
  local payload=""
  if [[ "${ident}" =~ ^[0-9]+$ ]]; then
    echo "${ident}"
    return 0
  fi
  payload="$(users_json)"
  python3 - "${ident}" "${payload}" <<'PY'
import json,sys
ident = sys.argv[1].strip().lower()
data = json.loads(sys.argv[2])
for u in data.get("users", []):
    if str(u.get("email", "")).strip().lower() == ident:
        print(u["id"])
        raise SystemExit(0)
raise SystemExit(1)
PY
}

print_users_table() {
  local payload="$1"
  python3 - "${payload}" <<'PY'
import json,sys
data = json.loads(sys.argv[1])
rows = data.get("users", [])
print(f"{'ID':<4} {'EMAIL':<36} {'ROLE':<7} {'ACTIVE':<7} {'LAST_LOGIN':<26}")
for u in rows:
    last_login = u.get("last_login_at") or "-"
    print(f"{u.get('id','-')!s:<4} {u.get('email','-'):<36} {u.get('role','user'):<7} {str(bool(u.get('is_active',0))):<7} {last_login:<26}")
PY
}

if [[ "${1:-}" == "" ]]; then
  usage
  exit 1
fi

cmd="$1"
shift

case "${cmd}" in
  list)
    users_payload="$(users_json)"
    print_users_table "${users_payload}"
    ;;

  add)
    email="${1:-}"
    password="${2:-}"
    role="${3:-user}"
    if [[ -z "${email}" ]]; then
      echo "Virhe: add vaatii emailin"
      exit 1
    fi
    if [[ -z "${password}" ]]; then
      password="$(rand_password)"
      generated=1
    else
      generated=0
    fi
    api_call "POST" "/admin/users" "{\"email\":\"${email}\",\"password\":\"${password}\",\"role\":\"${role}\"}" >/dev/null
    echo "Käyttäjä lisätty: ${email} (role=${role})"
    if [[ "${generated}" -eq 1 ]]; then
      echo "Väliaikainen salasana: ${password}"
    fi
    ;;

  disable|enable|remove)
    ident="${1:-}"
    if [[ -z "${ident}" ]]; then
      echo "Virhe: ${cmd} vaatii id:n tai emailin"
      exit 1
    fi
    user_id="$(resolve_user_id "${ident}")" || {
      echo "Käyttäjää ei löytynyt: ${ident}"
      exit 1
    }
    if [[ "${cmd}" == "disable" ]]; then
      api_call "POST" "/admin/users/${user_id}/disable" >/dev/null
      echo "Käyttäjä estetty (id=${user_id})"
    elif [[ "${cmd}" == "enable" ]]; then
      api_call "POST" "/admin/users/${user_id}/enable" >/dev/null
      echo "Käyttäjä aktivoitu (id=${user_id})"
    else
      api_call "DELETE" "/admin/users/${user_id}" >/dev/null
      echo "Käyttäjä poistettu pehmeästi (id=${user_id})"
    fi
    ;;

  reset-password)
    ident="${1:-}"
    new_password="${2:-}"
    if [[ -z "${ident}" ]]; then
      echo "Virhe: reset-password vaatii id:n tai emailin"
      exit 1
    fi
    user_id="$(resolve_user_id "${ident}")" || {
      echo "Käyttäjää ei löytynyt: ${ident}"
      exit 1
    }
    if [[ -z "${new_password}" ]]; then
      new_password="$(rand_password)"
      generated=1
    else
      generated=0
    fi
    api_call "POST" "/admin/users/${user_id}/reset-password" "{\"password\":\"${new_password}\"}" >/dev/null
    echo "Salasana nollattu (id=${user_id})"
    if [[ "${generated}" -eq 1 ]]; then
      echo "Uusi väliaikainen salasana: ${new_password}"
    fi
    ;;

  *)
    usage
    exit 1
    ;;
esac
