#!/bin/bash

# Security Configuration Test Script
# Tests production security configuration

GREEN="\e[32m"
YELLOW="\e[33m"
RED="\e[31m"
RESET="\e[0m"

BASE_URL="https://localhost"
USER_AGENT="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"

echo -e "${YELLOW}Testing Production Security Configuration${RESET}"
echo "================================================"

# Function to test HTTP endpoint
test_endpoint() {
    local path=$1
    local expected_status=$2
    local description=$3
    
    echo -e "\n${YELLOW}Testing: ${description}${RESET}"
    echo "Endpoint: ${path}"
    
    response=$(curl -s -o /dev/null -w "%{http_code}" \
        -H "User-Agent: $USER_AGENT" \
        "${BASE_URL}${path}" 2>/dev/null)
    
    if [ "$response" = "$expected_status" ]; then
        echo -e "${GREEN}✓ PASS${RESET} - Got expected status: $response"
    else
        echo -e "${RED}✗ FAIL${RESET} - Expected: $expected_status, Got: $response"
    fi
}

# Test blocked routes in production (should return 404)
echo -e "\n${YELLOW}=== Testing Blocked Routes ===${RESET}"
test_endpoint "/admin/discovery" "404" "Admin Discovery Route (blocked in production)"
test_endpoint "/admin/routes" "404" "Admin Routes Route (blocked in production)"
test_endpoint "/admin/performance" "404" "Admin Performance Route (blocked in production)"
test_endpoint "/debug" "404" "Debug Route (blocked in production)"

# Test IP-restricted routes (should return 403 from external IPs, but might be 200 from localhost)
echo -e "\n${YELLOW}=== Testing IP-Restricted Routes ===${RESET}"
test_endpoint "/admin" "200" "Admin Route (IP-restricted, should work from localhost)"
test_endpoint "/health" "200" "Health Route (IP-restricted, should work from localhost)"

# Test normal routes (should work)
echo -e "\n${YELLOW}=== Testing Normal Routes ===${RESET}"
test_endpoint "/" "200" "Home Route (should work)"
test_endpoint "/api/version" "200" "API Version Route (should work)"

echo -e "\n${YELLOW}=== Environment Configuration Test ===${RESET}"

# Check if APP_ENV is set correctly
if [ -f .env ]; then
    APP_ENV=$(grep "^APP_ENV=" .env | cut -d'=' -f2)
    APP_DEBUG=$(grep "^APP_DEBUG=" .env | cut -d'=' -f2)
    
    echo "APP_ENV: $APP_ENV"
    echo "APP_DEBUG: $APP_DEBUG"
    
    if [ "$APP_ENV" = "production" ] && [ "$APP_DEBUG" = "false" ]; then
        echo -e "${GREEN}✓ PASS${RESET} - Production environment correctly configured"
    else
        echo -e "${RED}✗ FAIL${RESET} - Environment not configured for production"
    fi
else
    echo -e "${RED}✗ FAIL${RESET} - .env file not found"
fi

echo -e "\n${YELLOW}Security test completed.${RESET}"
echo -e "\n${YELLOW}Note: For full production testing, deploy to production server and test from external IP.${RESET}"