#!/bin/bash
# Environment Setup Script for Royal Enfield Workflow Backend

echo "=================================================="
echo "Royal Enfield - Backend Environment Setup"
echo "=================================================="
echo ""

# Function to generate random secret
generate_secret() {
    openssl rand -base64 32 | tr -d "=+/" | cut -c1-32
}

# Function to create .env file
create_env_file() {
    local env_type=$1
    local file_name=$2
    
    echo ""
    echo "=================================================="
    echo "Creating ${env_type} Environment File"
    echo "=================================================="
    echo ""
    
    # Application Configuration
    read -p "Enter NODE_ENV (development/production) [default: development]: " NODE_ENV
    NODE_ENV=${NODE_ENV:-development}
    
    read -p "Enter PORT [default: 5000]: " PORT
    PORT=${PORT:-5000}
    
    read -p "Enter BASE_URL (backend deployed URL): " BASE_URL
    read -p "Enter FRONTEND_URL (frontend URL for CORS): " FRONTEND_URL
    
    # Database Configuration
    echo ""
    echo "--- Database Configuration ---"
    read -p "Enter DB_HOST [default: localhost]: " DB_HOST
    DB_HOST=${DB_HOST:-localhost}
    
    read -p "Enter DB_PORT [default: 5432]: " DB_PORT
    DB_PORT=${DB_PORT:-5432}
    
    read -p "Enter DB_NAME [default: re_workflow_db]: " DB_NAME
    DB_NAME=${DB_NAME:-re_workflow_db}
    
    read -p "Enter DB_USER: " DB_USER
    read -p "Enter DB_PASSWORD: " DB_PASSWORD
    
    # JWT Secrets
    echo ""
    echo "--- JWT Configuration ---"
    read -p "Generate JWT_SECRET automatically? (y/n) [default: y]: " GEN_JWT
    GEN_JWT=${GEN_JWT:-y}
    if [ "$GEN_JWT" = "y" ]; then
        JWT_SECRET=$(generate_secret)
        echo "✅ Generated JWT_SECRET"
    else
        read -p "Enter JWT_SECRET (min 32 chars): " JWT_SECRET
    fi
    
    read -p "Generate REFRESH_TOKEN_SECRET automatically? (y/n) [default: y]: " GEN_REFRESH
    GEN_REFRESH=${GEN_REFRESH:-y}
    if [ "$GEN_REFRESH" = "y" ]; then
        REFRESH_TOKEN_SECRET=$(generate_secret)
        echo "✅ Generated REFRESH_TOKEN_SECRET"
    else
        read -p "Enter REFRESH_TOKEN_SECRET: " REFRESH_TOKEN_SECRET
    fi
    
    # Session Secret
    read -p "Generate SESSION_SECRET automatically? (y/n) [default: y]: " GEN_SESSION
    GEN_SESSION=${GEN_SESSION:-y}
    if [ "$GEN_SESSION" = "y" ]; then
        SESSION_SECRET=$(generate_secret)
        echo "✅ Generated SESSION_SECRET"
    else
        read -p "Enter SESSION_SECRET (min 32 chars): " SESSION_SECRET
    fi
    
    # Okta Configuration
    echo ""
    echo "--- Okta SSO Configuration ---"
    read -p "Enter OKTA_DOMAIN: " OKTA_DOMAIN
    read -p "Enter OKTA_CLIENT_ID: " OKTA_CLIENT_ID
    read -p "Enter OKTA_CLIENT_SECRET: " OKTA_CLIENT_SECRET
    read -p "Enter OKTA_API_TOKEN (optional): " OKTA_API_TOKEN
    
    # VAPID Keys for Web Push
    echo ""
    echo "--- Web Push (VAPID) Configuration ---"
    echo "Note: VAPID keys are required for push notifications."
    echo "Run 'npx web-push generate-vapid-keys' to generate them, or enter manually."
    read -p "Enter VAPID_PUBLIC_KEY (or press Enter to skip): " VAPID_PUBLIC_KEY
    read -p "Enter VAPID_PRIVATE_KEY (or press Enter to skip): " VAPID_PRIVATE_KEY
    read -p "Enter VAPID_CONTACT email [default: mailto:admin@example.com]: " VAPID_CONTACT
    VAPID_CONTACT=${VAPID_CONTACT:-mailto:admin@example.com}
    
    # Redis Configuration
    echo ""
    echo "--- Redis Configuration (for TAT Queue) ---"
    read -p "Enter REDIS_URL [default: redis://localhost:6379]: " REDIS_URL
    REDIS_URL=${REDIS_URL:-redis://localhost:6379}
    
    # Optional Services
    echo ""
    echo "--- Optional Services ---"
    read -p "Enter SMTP_HOST (or press Enter to skip): " SMTP_HOST
    read -p "Enter SMTP_USER (or press Enter to skip): " SMTP_USER
    read -p "Enter SMTP_PASSWORD (or press Enter to skip): " SMTP_PASSWORD
    
    read -p "Enter GCP_PROJECT_ID (or press Enter to skip): " GCP_PROJECT_ID
    read -p "Enter GCP_BUCKET_NAME (or press Enter to skip): " GCP_BUCKET_NAME
    
    # Vertex AI Configuration
    echo ""
    echo "--- Vertex AI Gemini Configuration (Optional) ---"
    echo "Note: These have defaults and are optional. Service account credentials are required."
    read -p "Enter VERTEX_AI_MODEL [default: gemini-2.5-flash]: " VERTEX_AI_MODEL
    VERTEX_AI_MODEL=${VERTEX_AI_MODEL:-gemini-2.5-flash}
    
    read -p "Enter VERTEX_AI_LOCATION [default: us-central1]: " VERTEX_AI_LOCATION
    VERTEX_AI_LOCATION=${VERTEX_AI_LOCATION:-us-central1}
    
    # Create .env file
    cat > "$file_name" << EOF
# Application
NODE_ENV=${NODE_ENV}
PORT=${PORT}
API_VERSION=v1
BASE_URL=${BASE_URL}
FRONTEND_URL=${FRONTEND_URL}

# Database
DB_HOST=${DB_HOST}
DB_PORT=${DB_PORT}
DB_NAME=${DB_NAME}
DB_USER=${DB_USER}
DB_PASSWORD=${DB_PASSWORD}
DB_SSL=false
DB_POOL_MIN=2
DB_POOL_MAX=10

# SSO Configuration (Frontend-handled)
# Backend only needs JWT secrets for token validation
JWT_SECRET=${JWT_SECRET}
JWT_EXPIRY=24h
REFRESH_TOKEN_SECRET=${REFRESH_TOKEN_SECRET}
REFRESH_TOKEN_EXPIRY=7d

# Session
SESSION_SECRET=${SESSION_SECRET}

# Cloud Storage (GCP)
GCP_PROJECT_ID=${GCP_PROJECT_ID}
GCP_BUCKET_NAME=${GCP_BUCKET_NAME}
GCP_KEY_FILE=./config/gcp-key.json

# Email Service (Optional)
SMTP_HOST=${SMTP_HOST}
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER=${SMTP_USER}
SMTP_PASSWORD=${SMTP_PASSWORD}
EMAIL_FROM=RE Workflow System <notifications@{{APP_DOMAIN}}>

# Vertex AI Gemini Configuration (for conclusion generation)
# Service account credentials should be placed in ./credentials/ folder
VERTEX_AI_MODEL=${VERTEX_AI_MODEL}
VERTEX_AI_LOCATION=${VERTEX_AI_LOCATION}

# Logging
LOG_LEVEL=info
LOG_FILE_PATH=./logs

# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100

# File Upload
MAX_FILE_SIZE_MB=10
ALLOWED_FILE_TYPES=pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif

# TAT Monitoring
TAT_CHECK_INTERVAL_MINUTES=30
TAT_REMINDER_THRESHOLD_1=50
TAT_REMINDER_THRESHOLD_2=80
OKTA_API_TOKEN=${OKTA_API_TOKEN}
OKTA_DOMAIN=${OKTA_DOMAIN}
OKTA_CLIENT_ID=${OKTA_CLIENT_ID}
OKTA_CLIENT_SECRET=${OKTA_CLIENT_SECRET}

# Notification Service Worker credentials (Web Push / VAPID)
VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY}
VAPID_PRIVATE_KEY=${VAPID_PRIVATE_KEY}
VAPID_CONTACT=${VAPID_CONTACT}

# Redis (for TAT Queue)
REDIS_URL=${REDIS_URL}
TAT_TEST_MODE=false
EOF
    
    echo ""
    echo "✅ Created ${file_name}"
}

# Function to show VAPID key generation instructions
show_vapid_instructions() {
    echo ""
    echo "=================================================="
    echo "VAPID Key Generation Instructions"
    echo "=================================================="
    echo ""
    echo "VAPID (Voluntary Application Server Identification) keys are required"
    echo "for web push notifications. You need to generate a key pair:"
    echo ""
    echo "1. Generate VAPID keys using npx (no installation needed):"
    echo "   npx web-push generate-vapid-keys"
    echo ""
    echo "   This will output:"
    echo "   ================================================"
    echo "   Public Key: <your-public-key>"
    echo "   Private Key: <your-private-key>"
    echo "   ================================================"
    echo ""
    echo "3. Add the keys to your .env file:"
    echo "   VAPID_PUBLIC_KEY=<your-public-key>"
    echo "   VAPID_PRIVATE_KEY=<your-private-key>"
    echo "   VAPID_CONTACT=mailto:your-email@example.com"
    echo ""
    echo "4. IMPORTANT: Add the SAME VAPID_PUBLIC_KEY to your frontend .env file:"
    echo "   VITE_PUBLIC_VAPID_KEY=<your-public-key>"
    echo ""
    echo "5. The VAPID_CONTACT should be a valid mailto: URL"
    echo "   Example: mailto:admin@{{APP_DOMAIN}}"
    echo ""
    echo "Note: Keep your VAPID_PRIVATE_KEY secure and never commit it to version control!"
    echo ""
}

# Main execution
echo "This script will help you create environment configuration files for your backend."
echo ""
echo "Options:"
echo "1. Create .env file (interactive)"
echo "2. Show VAPID key generation instructions"
echo "3. Exit"
echo ""
read -p "Select an option (1-3): " OPTION

case $OPTION in
    1)
        create_env_file "Development" ".env"
        echo ""
        echo "=================================================="
        echo "Setup Complete!"
        echo "=================================================="
        echo ""
        echo "Next Steps:"
        echo ""
        echo "1. Generate VAPID keys for web push notifications:"
        echo "   npx web-push generate-vapid-keys"
        echo "   Then add them to your .env file"
        echo ""
        echo "2. Set up your database:"
        echo "   - Ensure PostgreSQL is running"
        echo "   - Run migrations if needed"
        echo ""
        echo "3. Set up Redis (for TAT queue):"
        echo "   - Install and start Redis"
        echo "   - Update REDIS_URL in .env"
        echo ""
        echo "4. Start the backend:"
        echo "   npm run dev"
        echo ""
        ;;
    2)
        show_vapid_instructions
        ;;
    3)
        echo "Exiting..."
        exit 0
        ;;
    *)
        echo "Invalid option. Exiting..."
        exit 1
        ;;
esac

