#!/bin/bash

# =============================================================================
# Environment Variables Validation Script
# =============================================================================
# This script validates that all required environment variables are set
# before starting docker-compose services.
#
# Usage:
#   ./scripts/validate-env.sh [environment]
#   environment: local (default), production, test
#
# =============================================================================

set -e

ENVIRONMENT=${1:-local}
ENV_FILE=".env"

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

echo "🔍 Validating environment variables for: ${ENVIRONMENT}"

# Check if .env file exists
if [ ! -f "${ENV_FILE}" ]; then
    echo -e "${RED}❌ Error: .env file not found!${NC}"
    echo -e "${YELLOW}💡 Tip: Copy .env.example to .env and configure it:${NC}"
    echo "   cp .env.example .env"
    exit 1
fi

# Load environment variables
set -a
source "${ENV_FILE}"
set +a

# Track validation errors
ERRORS=0
WARNINGS=0

# Function to check if variable is set
check_var() {
    local var_name=$1
    local required=$2
    local value="${!var_name}"
    
    if [ -z "$value" ]; then
        if [ "$required" = "required" ]; then
            echo -e "${RED}❌ ${var_name} is required but not set${NC}"
            ERRORS=$((ERRORS + 1))
        else
            echo -e "${YELLOW}⚠️  ${var_name} is not set (optional)${NC}"
            WARNINGS=$((WARNINGS + 1))
        fi
    else
        echo -e "${GREEN}✅ ${var_name} is set${NC}"
    fi
}

# Function to validate password strength
validate_password() {
    local var_name=$1
    local value="${!var_name}"
    
    if [ -z "$value" ]; then
        return 0
    fi
    
    if [ ${#value} -lt 8 ]; then
        echo -e "${YELLOW}⚠️  ${var_name} is too short (minimum 8 characters recommended)${NC}"
        WARNINGS=$((WARNINGS + 1))
    fi
}

# Function to validate URL format
validate_url() {
    local var_name=$1
    local value="${!var_name}"
    local scheme=$2  # http, https, ws, wss, postgres, redis
    
    if [ -z "$value" ]; then
        return 0
    fi
    
    if [[ ! "$value" =~ ^${scheme}:// ]]; then
        echo -e "${YELLOW}⚠️  ${var_name} should start with ${scheme}://${NC}"
        WARNINGS=$((WARNINGS + 1))
    fi
}

echo ""
echo "📋 Checking required variables..."

# Required variables for all environments
check_var "POSTGRES_DB" "required"
check_var "POSTGRES_USER" "required"
check_var "POSTGRES_PASSWORD" "required"
check_var "DATABASE_URL" "required"
check_var "REDIS_URL" "required"
check_var "JWT_SECRET" "required"
check_var "VITE_API_URL" "required"
check_var "VITE_WS_URL" "required"
check_var "VITE_STREAM_URL" "required"

# Production-specific requirements
if [ "$ENVIRONMENT" = "production" ]; then
    echo ""
    echo "🔒 Checking production-specific requirements..."
    
    check_var "REDIS_PASSWORD" "required"
    
    # Validate password strength
    validate_password "POSTGRES_PASSWORD"
    validate_password "REDIS_PASSWORD"
    validate_password "JWT_SECRET"
    
    # Validate URLs use secure protocols
    if [[ ! "$VITE_API_URL" =~ ^https:// ]]; then
        echo -e "${YELLOW}⚠️  VITE_API_URL should use HTTPS in production${NC}"
        WARNINGS=$((WARNINGS + 1))
    fi
    
    if [[ ! "$VITE_WS_URL" =~ ^wss:// ]]; then
        echo -e "${YELLOW}⚠️  VITE_WS_URL should use WSS in production${NC}"
        WARNINGS=$((WARNINGS + 1))
    fi
    
    if [[ ! "$VITE_STREAM_URL" =~ ^wss:// ]]; then
        echo -e "${YELLOW}⚠️  VITE_STREAM_URL should use WSS in production${NC}"
        WARNINGS=$((WARNINGS + 1))
    fi
    
    # Check for default/weak values
    if [ "$JWT_SECRET" = "your-secret-key-here-change-in-production" ] || [ "$JWT_SECRET" = "dev-secret-key-change-in-production" ]; then
        echo -e "${RED}❌ JWT_SECRET is still using default value! Change it in production.${NC}"
        ERRORS=$((ERRORS + 1))
    fi
    
    if [ "$POSTGRES_PASSWORD" = "veza_password" ]; then
        echo -e "${RED}❌ POSTGRES_PASSWORD is still using default value! Change it in production.${NC}"
        ERRORS=$((ERRORS + 1))
    fi
fi

# Validate URL formats
echo ""
echo "🔗 Validating URL formats..."
validate_url "DATABASE_URL" "postgres"
validate_url "REDIS_URL" "redis"
validate_url "VITE_API_URL" "http"
validate_url "VITE_WS_URL" "ws"
validate_url "VITE_STREAM_URL" "ws"

# Summary
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
if [ $ERRORS -eq 0 ] && [ $WARNINGS -eq 0 ]; then
    echo -e "${GREEN}✅ All checks passed!${NC}"
    exit 0
elif [ $ERRORS -eq 0 ]; then
    echo -e "${YELLOW}⚠️  Validation completed with ${WARNINGS} warning(s)${NC}"
    echo -e "${GREEN}✅ No critical errors${NC}"
    exit 0
else
    echo -e "${RED}❌ Validation failed with ${ERRORS} error(s) and ${WARNINGS} warning(s)${NC}"
    echo ""
    echo "Please fix the errors before starting docker-compose."
    exit 1
fi

