#!/bin/bash
# =====================================================
# Smoke Tests for Mawidi Platform
# =====================================================
# Quick verification that critical functionality works after deployment
#
# Usage:
#   ./scripts/smoke-test.sh <environment>
#
# Examples:
#   ./scripts/smoke-test.sh development
#   ./scripts/smoke-test.sh staging
#   ./scripts/smoke-test.sh production
#
# Exit codes:
#   0 = All tests passed
#   1 = One or more tests failed

set -e

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

# Configuration
ENVIRONMENT=${1:-development}
TIMEOUT=10

# Set base URL based on environment
case $ENVIRONMENT in
  production)
    BASE_URL="https://mawidi.com"
    ;;
  staging)
    BASE_URL="https://staging.mawidi.com"
    ;;
  development|dev)
    BASE_URL="https://dev.mawidi.com"
    ;;
  local)
    BASE_URL="http://localhost:9000"
    ;;
  *)
    echo -e "${RED}❌ Invalid environment: $ENVIRONMENT${NC}"
    echo "Usage: $0 <development|staging|production|local>"
    exit 1
    ;;
esac

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Mawidi Smoke Tests${NC}"
echo -e "${BLUE}========================================${NC}"
echo -e "${YELLOW}Environment: $ENVIRONMENT${NC}"
echo -e "${YELLOW}Base URL: $BASE_URL${NC}"
echo ""

# Test counter
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

# =====================================================
# Helper Functions
# =====================================================

run_test() {
  local test_name=$1
  local url=$2
  local expected_status=${3:-200}
  local search_text=$4

  TOTAL_TESTS=$((TOTAL_TESTS + 1))
  echo -ne "${BLUE}Test $TOTAL_TESTS: $test_name...${NC} "

  # Make request
  response=$(curl -s -o /dev/null -w "%{http_code}:%{time_total}" --max-time $TIMEOUT "$url" 2>&1)

  # Parse response
  http_code=$(echo $response | cut -d: -f1)
  time_total=$(echo $response | cut -d: -f2)

  # Check HTTP status code
  if [ "$http_code" -eq "$expected_status" ]; then
    # If search text provided, verify it exists
    if [ -n "$search_text" ]; then
      content=$(curl -s --max-time $TIMEOUT "$url" 2>&1)
      if echo "$content" | grep -q "$search_text"; then
        echo -e "${GREEN}✅ PASS${NC} (${http_code}, ${time_total}s)"
        PASSED_TESTS=$((PASSED_TESTS + 1))
      else
        echo -e "${RED}❌ FAIL${NC} (content check failed)"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        return 1
      fi
    else
      echo -e "${GREEN}✅ PASS${NC} (${http_code}, ${time_total}s)"
      PASSED_TESTS=$((PASSED_TESTS + 1))
    fi
  else
    echo -e "${RED}❌ FAIL${NC} (expected $expected_status, got $http_code)"
    FAILED_TESTS=$((FAILED_TESTS + 1))
    return 1
  fi
}

run_json_test() {
  local test_name=$1
  local url=$2
  local json_field=$3
  local expected_value=$4

  TOTAL_TESTS=$((TOTAL_TESTS + 1))
  echo -ne "${BLUE}Test $TOTAL_TESTS: $test_name...${NC} "

  # Make request and parse JSON
  response=$(curl -s --max-time $TIMEOUT "$url" 2>&1)

  if command -v jq &> /dev/null; then
    actual_value=$(echo "$response" | jq -r ".$json_field" 2>/dev/null)

    if [ "$actual_value" = "$expected_value" ]; then
      echo -e "${GREEN}✅ PASS${NC} ($json_field = $actual_value)"
      PASSED_TESTS=$((PASSED_TESTS + 1))
    else
      echo -e "${RED}❌ FAIL${NC} (expected $expected_value, got $actual_value)"
      FAILED_TESTS=$((FAILED_TESTS + 1))
      return 1
    fi
  else
    # Fallback without jq
    if echo "$response" | grep -q "\"$json_field\":\"$expected_value\""; then
      echo -e "${GREEN}✅ PASS${NC}"
      PASSED_TESTS=$((PASSED_TESTS + 1))
    else
      echo -e "${RED}❌ FAIL${NC} (jq not installed for detailed check)"
      FAILED_TESTS=$((FAILED_TESTS + 1))
      return 1
    fi
  fi
}

# =====================================================
# Critical Path Tests
# =====================================================

echo -e "${YELLOW}Running critical path tests...${NC}"
echo ""

# Test 1: Main health endpoint
run_test "Health Check" "$BASE_URL/api/health" 200

# Test 2: Detailed health check
run_json_test "Detailed Health Check" "$BASE_URL/api/health/detailed" "status" "healthy"

# Test 3: Database health
run_json_test "Database Health" "$BASE_URL/api/health/database" "healthy" "true"

# Test 4: Redis health (may be not configured)
run_test "Redis Health" "$BASE_URL/api/health/redis" 200

# Test 5: Supabase health
run_test "Supabase Health" "$BASE_URL/api/health/supabase" 200

# Test 6: Liveness probe
run_json_test "Liveness Probe" "$BASE_URL/api/health/live" "alive" "true"

# Test 7: Readiness probe
run_json_test "Readiness Probe" "$BASE_URL/api/health/ready" "ready" "true"

echo ""
echo -e "${YELLOW}Running page accessibility tests...${NC}"
echo ""

# Test 8: Homepage (Arabic)
run_test "Homepage (Arabic)" "$BASE_URL/ar" 200

# Test 9: Homepage (English)
run_test "Homepage (English)" "$BASE_URL/en" 200

# Test 10: About page
run_test "About Page" "$BASE_URL/en/about" 200

# Test 11: Pricing page
run_test "Pricing Page" "$BASE_URL/en/pricing" 200

# Test 12: Contact page
run_test "Contact Page" "$BASE_URL/en/contact" 200

# Test 13: Demo booking page
run_test "Demo Booking Page" "$BASE_URL/en/demo" 200

# Test 14: Login page
run_test "Login Page" "$BASE_URL/en/login" 200

# Test 15: Signup page
run_test "Signup Page" "$BASE_URL/en/signup" 200

echo ""
echo -e "${YELLOW}Running API endpoint tests...${NC}"
echo ""

# Test 16: Status endpoint
run_test "Status API" "$BASE_URL/api/status" 200

# Test 17: Health endpoint (HEAD request)
http_code=$(curl -s -o /dev/null -w "%{http_code}" -I --max-time $TIMEOUT "$BASE_URL/api/health")
TOTAL_TESTS=$((TOTAL_TESTS + 1))
if [ "$http_code" -eq 200 ]; then
  echo -e "${BLUE}Test $TOTAL_TESTS: Health API (HEAD)...${NC} ${GREEN}✅ PASS${NC} ($http_code)"
  PASSED_TESTS=$((PASSED_TESTS + 1))
else
  echo -e "${BLUE}Test $TOTAL_TESTS: Health API (HEAD)...${NC} ${RED}❌ FAIL${NC} ($http_code)"
  FAILED_TESTS=$((FAILED_TESTS + 1))
fi

# =====================================================
# Performance Tests
# =====================================================

echo ""
echo -e "${YELLOW}Running performance tests...${NC}"
echo ""

# Test 18: Homepage load time (should be < 3 seconds)
TOTAL_TESTS=$((TOTAL_TESTS + 1))
response_time=$(curl -s -o /dev/null -w "%{time_total}" --max-time $TIMEOUT "$BASE_URL/en" 2>&1)
response_time_ms=$(echo "$response_time * 1000" | bc 2>/dev/null || echo "0")

echo -ne "${BLUE}Test $TOTAL_TESTS: Homepage Performance...${NC} "
if (( $(echo "$response_time < 3.0" | bc -l 2>/dev/null || echo 0) )); then
  echo -e "${GREEN}✅ PASS${NC} (${response_time}s)"
  PASSED_TESTS=$((PASSED_TESTS + 1))
else
  echo -e "${YELLOW}⚠️  SLOW${NC} (${response_time}s > 3.0s)"
  PASSED_TESTS=$((PASSED_TESTS + 1))  # Still pass, just warn
fi

# =====================================================
# Results Summary
# =====================================================

echo ""
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Test Results Summary${NC}"
echo -e "${BLUE}========================================${NC}"
echo -e "Total Tests: $TOTAL_TESTS"
echo -e "${GREEN}Passed: $PASSED_TESTS${NC}"
if [ $FAILED_TESTS -gt 0 ]; then
  echo -e "${RED}Failed: $FAILED_TESTS${NC}"
else
  echo -e "Failed: $FAILED_TESTS"
fi
echo ""

# Exit code based on results
if [ $FAILED_TESTS -eq 0 ]; then
  echo -e "${GREEN}========================================${NC}"
  echo -e "${GREEN}✅ ALL SMOKE TESTS PASSED${NC}"
  echo -e "${GREEN}========================================${NC}"
  echo ""
  echo -e "${GREEN}✅ $ENVIRONMENT environment is healthy${NC}"
  echo -e "${GREEN}✅ Safe to proceed with deployment${NC}"
  exit 0
else
  echo -e "${RED}========================================${NC}"
  echo -e "${RED}❌ SMOKE TESTS FAILED${NC}"
  echo -e "${RED}========================================${NC}"
  echo ""
  echo -e "${RED}❌ $FAILED_TESTS test(s) failed${NC}"
  echo -e "${RED}❌ DO NOT deploy to production${NC}"
  echo -e "${YELLOW}⚠️  Investigate failures before proceeding${NC}"
  exit 1
fi
