#!/bin/bash
# Approve a user and assign track level

set -e

if [ $# -lt 2 ]; then
    echo "Usage: $0 <address> <track_level> [approved_by]"
    echo ""
    echo "Examples:"
    echo "  $0 0x1234...5678 2"
    echo "  $0 0x1234...5678 3 0xAdminAddress"
    echo ""
    echo "Track levels:"
    echo "  1 = Public (default, no approval needed)"
    echo "  2 = Approved users (full indexed explorer)"
    echo "  3 = Analytics users"
    echo "  4 = Operators"
    exit 1
fi

ADDRESS="$1"
TRACK="$2"
APPROVED_BY="${3:-system}"

# Load database config
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-5432}"
DB_USER="${DB_USER:-explorer}"
DB_PASSWORD="${DB_PASSWORD:-changeme}"
DB_NAME="${DB_NAME:-explorer}"

export PGPASSWORD="$DB_PASSWORD"

echo "Approving user: $ADDRESS"
echo "Track level: $TRACK"
echo "Approved by: $APPROVED_BY"
echo ""

# Insert or update operator role
QUERY="
INSERT INTO operator_roles (address, track_level, approved, approved_by, approved_at)
VALUES (\$1, \$2, TRUE, \$3, NOW())
ON CONFLICT (address) DO UPDATE SET
    track_level = EXCLUDED.track_level,
    approved = TRUE,
    approved_by = EXCLUDED.approved_by,
    approved_at = NOW(),
    updated_at = NOW();
"

if psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" \
    -c "$QUERY" \
    -v address="$ADDRESS" \
    -v track="$TRACK" \
    -v approved_by="$APPROVED_BY"; then
    echo "✅ User approved successfully"
else
    echo "❌ Failed to approve user"
    exit 1
fi

unset PGPASSWORD

