#!/usr/bin/env bash
# Vault Setup Script for Development Environment
# Creates AppRole, policies, and secrets for dev services
set -euo pipefail

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

# Source the vlt helper
VLT="${REPO_ROOT}/ci/vlt"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

log() { echo -e "${GREEN}[vault-setup]${NC} $*"; }
warn() { echo -e "${YELLOW}[vault-setup]${NC} $*"; }
error() { echo -e "${RED}[vault-setup]${NC} $*" >&2; }

# Check prerequisites
if [ ! -f "$VLT" ]; then
  error "Vault helper not found at $VLT"
  exit 1
fi

if [ -z "${VAULT_ADDR:-}" ]; then
  error "VAULT_ADDR is not set"
  error "Please ensure Vault is running: cd infra/vault && docker compose up -d"
  exit 1
fi

log "Checking Vault connection..."
if ! curl -sf "${VAULT_ADDR}/v1/sys/health" > /dev/null; then
  error "Cannot connect to Vault at ${VAULT_ADDR}"
  error "Please ensure Vault is running: cd infra/vault && docker compose up -d"
  exit 1
fi

log "✓ Vault is reachable at ${VAULT_ADDR}"

# You need to be authenticated to Vault to run this script
# Either set VAULT_TOKEN or VAULT_ROLE_ID + VAULT_SECRET_ID
if [ -z "${VAULT_TOKEN:-}" ]; then
  warn "VAULT_TOKEN not set. Attempting AppRole login..."
  if [ -z "${VAULT_ROLE_ID:-}" ] || [ -z "${VAULT_SECRET_ID:-}" ]; then
    error "Neither VAULT_TOKEN nor VAULT_ROLE_ID/VAULT_SECRET_ID are set"
    error "Please authenticate to Vault first:"
    error "  export VAULT_TOKEN=<your-vault-token>"
    error "Or use AppRole:"
    error "  export VAULT_ROLE_ID=<role-id>"
    error "  export VAULT_SECRET_ID=<secret-id>"
    exit 1
  fi
  "${VLT}" login
  VAULT_TOKEN="$(cat .vault_token)"
  export VAULT_TOKEN
fi

log "Creating dev environment policy..."
cat <<'EOF' | curl -sf -X PUT -H "X-Vault-Token: ${VAULT_TOKEN}" \
  --data-binary @- "${VAULT_ADDR}/v1/sys/policy/dev-services" > /dev/null
{
  "policy": "path \"kv/data/sendico/dev\" { capabilities = [\"read\"] }"
}
EOF

log "Creating dev-services AppRole..."
curl -sf -X POST -H "X-Vault-Token: ${VAULT_TOKEN}" \
  -d '{"policies": ["dev-services"], "bind_secret_id": true, "token_ttl": "24h", "token_max_ttl": "720h"}' \
  "${VAULT_ADDR}/v1/auth/approle/role/dev-services" > /dev/null

log "Fetching AppRole credentials..."
ROLE_ID=$(curl -sf -H "X-Vault-Token: ${VAULT_TOKEN}" \
  "${VAULT_ADDR}/v1/auth/approle/role/dev-services/role-id" | \
  grep -o '"role_id":"[^"]*' | cut -d'"' -f4)

SECRET_ID=$(curl -sf -X POST -H "X-Vault-Token: ${VAULT_TOKEN}" \
  "${VAULT_ADDR}/v1/auth/approle/role/dev-services/secret-id" | \
  grep -o '"secret_id":"[^"]*' | cut -d'"' -f4)

log "Creating/updating dev secrets in Vault..."

# Generate random credentials if they don't exist
MONGO_USER="sendico_dev"
MONGO_PASSWORD="$(openssl rand -base64 32 | tr -d '/+=' | cut -c1-24)"
MONGO_KEYFILE="$(openssl rand -base64 756 | tr -d '\n')"
NATS_USER="sendico_dev"
NATS_PASSWORD="$(openssl rand -base64 32 | tr -d '/+=' | cut -c1-24)"

curl -sf -X POST -H "X-Vault-Token: ${VAULT_TOKEN}" \
  -d "{
    \"data\": {
      \"mongo_user\": \"${MONGO_USER}\",
      \"mongo_password\": \"${MONGO_PASSWORD}\",
      \"mongo_keyfile\": \"${MONGO_KEYFILE}\",
      \"nats_user\": \"${NATS_USER}\",
      \"nats_password\": \"${NATS_PASSWORD}\"
    }
  }" \
  "${VAULT_ADDR}/v1/kv/data/sendico/dev" > /dev/null

log "✅ Vault setup complete!"
echo ""
log "AppRole Credentials (add these to .env.dev):"
echo ""
echo "VAULT_ROLE_ID=${ROLE_ID}"
echo "VAULT_SECRET_ID=${SECRET_ID}"
echo ""
warn "IMPORTANT: Save these credentials in .env.dev"
warn "They will be needed to start the dev environment"
