#!/bin/bash

# Smoke Test Script for Docker Compose Stack
# Tests health endpoints, tenant creation, and key API endpoints for all services

set -e

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

# Configuration
BASE_URL="${BASE_URL:-localhost}"
PROTOCOL="${PROTOCOL:-http}"
TEST_EMAIL="smoke@dd0c.dev"
TEST_PASSWORD="smoketest123!"
TEST_TENANT="smoke-test"

# Counters
TOTAL_CHECKS=0
PASSED_CHECKS=0

# Help function
show_help() {
  cat << EOF
Smoke Test Script for Docker Compose Stack

Usage: $0 [OPTIONS]

Options:
  --help              Show this help message
  --base-url URL      Set base URL (default: localhost)
  --protocol PROTO    Set protocol (default: http)

Environment Variables:
  BASE_URL            Override base URL (default: localhost)
  PROTOCOL            Override protocol (default: http)

Examples:
  $0
  $0 --base-url example.com --protocol https
  BASE_URL=192.168.1.100 $0

EOF
}

# Parse arguments
while [[ $# -gt 0 ]]; do
  case $1 in
    --help)
      show_help
      exit 0
      ;;
    --base-url)
      BASE_URL="$2"
      shift 2
      ;;
    --protocol)
      PROTOCOL="$2"
      shift 2
      ;;
    *)
      echo "Unknown option: $1"
      show_help
      exit 1
      ;;
  esac
done

# Helper functions
log_check() {
  local name=$1
  local status=$2
  ((TOTAL_CHECKS++))
  
  if [ "$status" = "pass" ]; then
    echo -e "${GREEN}✓${NC} $name"
    ((PASSED_CHECKS++))
  else
    echo -e "${RED}✗${NC} $name"
  fi
}

check_health() {
  local service=$1
  local check_cmd=$2
  
  if eval "$check_cmd" > /dev/null 2>&1; then
    log_check "Health: $service" "pass"
  else
    log_check "Health: $service" "fail"
  fi
}

create_tenant() {
  local port=$1
  local service=$2
  
  local response=$(curl -s -X POST \
    "${PROTOCOL}://${BASE_URL}:${port}/api/v1/auth/signup" \
    -H "Content-Type: application/json" \
    -d "{
      \"email\": \"${TEST_EMAIL}\",
      \"password\": \"${TEST_PASSWORD}\",
      \"tenant_name\": \"${TEST_TENANT}\"
    }" 2>/dev/null || echo "")
  
  local token=$(echo "$response" | grep -o '"token":"[^"]*' | cut -d'"' -f4 || echo "")
  
  if [ -n "$token" ]; then
    log_check "Tenant Creation: $service (port $port)" "pass"
    echo "$token"
  else
    log_check "Tenant Creation: $service (port $port)" "fail"
    echo ""
  fi
}

test_endpoint() {
  local port=$1
  local service=$2
  local endpoint=$3
  local token=$4
  
  if [ -z "$token" ]; then
    log_check "Endpoint: $service - $endpoint" "fail"
    return
  fi
  
  local http_code=$(curl -s -o /dev/null -w "%{http_code}" \
    -H "Authorization: Bearer $token" \
    "${PROTOCOL}://${BASE_URL}:${port}${endpoint}" 2>/dev/null || echo "000")
  
  if [ "$http_code" = "200" ] || [ "$http_code" = "201" ]; then
    log_check "Endpoint: $service - $endpoint" "pass"
  else
    log_check "Endpoint: $service - $endpoint (HTTP $http_code)" "fail"
  fi
}

# Main execution
echo -e "${YELLOW}=== Smoke Test Starting ===${NC}\n"

# 1. Health Checks
echo -e "${YELLOW}--- Health Checks ---${NC}"
check_health "PostgreSQL" "pg_isready -h ${BASE_URL} 2>/dev/null"
check_health "Redis" "redis-cli -h ${BASE_URL} ping > /dev/null 2>&1"

for port in 3003 3004 3005 3006; do
  check_health "HTTP Service (port $port)" "curl -s -o /dev/null -w '%{http_code}' ${PROTOCOL}://${BASE_URL}:${port}/health 2>/dev/null | grep -q '200'"
done

echo ""

# 2. Tenant Creation & API Tests
echo -e "${YELLOW}--- Tenant Creation & API Tests ---${NC}"

# P3 (port 3003)
echo -e "\n${YELLOW}P3 (port 3003):${NC}"
P3_TOKEN=$(create_tenant 3003 "P3")
test_endpoint 3003 "P3" "/api/v1/incidents" "$P3_TOKEN"
test_endpoint 3003 "P3" "/api/v1/summary" "$P3_TOKEN"

# P4 (port 3004)
echo -e "\n${YELLOW}P4 (port 3004):${NC}"
P4_TOKEN=$(create_tenant 3004 "P4")
test_endpoint 3004 "P4" "/api/v1/services" "$P4_TOKEN"
test_endpoint 3004 "P4" "/api/v1/discovery/history" "$P4_TOKEN"

# P5 (port 3005)
echo -e "\n${YELLOW}P5 (port 3005):${NC}"
P5_TOKEN=$(create_tenant 3005 "P5")
test_endpoint 3005 "P5" "/api/v1/anomalies" "$P5_TOKEN"
test_endpoint 3005 "P5" "/api/v1/baselines" "$P5_TOKEN"
test_endpoint 3005 "P5" "/api/v1/governance" "$P5_TOKEN"

# P6 (port 3006)
echo -e "\n${YELLOW}P6 (port 3006):${NC}"
P6_TOKEN=$(create_tenant 3006 "P6")
test_endpoint 3006 "P6" "/api/v1/runbooks" "$P6_TOKEN"
test_endpoint 3006 "P6" "/api/v1/approvals" "$P6_TOKEN"

# Summary
echo ""
echo -e "${YELLOW}=== Summary ===${NC}"
if [ $PASSED_CHECKS -eq $TOTAL_CHECKS ]; then
  echo -e "${GREEN}$PASSED_CHECKS/$TOTAL_CHECKS passed${NC}"
  exit 0
else
  echo -e "${RED}$PASSED_CHECKS/$TOTAL_CHECKS passed${NC}"
  exit 1
fi
