#!/usr/bin/env bash
# Create admin user for Token Aggregation Control Panel

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

# Load environment
if [[ -f "$PROJECT_ROOT/smom-dbis-138/services/token-aggregation/.env" ]]; then
  source "$PROJECT_ROOT/smom-dbis-138/services/token-aggregation/.env"
fi

DATABASE_URL="${DATABASE_URL:-postgresql://postgres:postgres@localhost:5432/explorer_db}"

echo "Creating admin user for Token Aggregation Control Panel"
echo ""

read -p "Username: " USERNAME
read -sp "Password: " PASSWORD
echo ""
read -p "Email (optional): " EMAIL
read -p "Role (super_admin/admin/operator/viewer) [admin]: " ROLE
ROLE="${ROLE:-admin}"

# Hash password using Node.js (with error handling)
if ! command -v node &> /dev/null; then
    echo "❌ Node.js not found. Please install Node.js to create admin users."
    exit 1
fi

PASSWORD_HASH=$(node -e "const bcrypt = require('bcrypt'); bcrypt.hash('$PASSWORD', 10).then(h => console.log(h)).catch(e => {console.error('Error:', e.message); process.exit(1);})" 2>&1)

if [[ $? -ne 0 ]] || [[ -z "$PASSWORD_HASH" ]]; then
    echo "❌ Failed to hash password. Make sure bcrypt is installed: npm install bcrypt"
    exit 1
fi

# Insert into database
psql "$DATABASE_URL" <<EOF
INSERT INTO admin_users (username, email, password_hash, role, is_active)
VALUES ('$USERNAME', '$EMAIL', '$PASSWORD_HASH', '$ROLE', true)
ON CONFLICT (username) DO UPDATE SET
  password_hash = EXCLUDED.password_hash,
  role = EXCLUDED.role,
  updated_at = NOW();
EOF

echo ""
echo "Admin user created successfully!"
echo "Username: $USERNAME"
echo "Role: $ROLE"
