#!/bin/bash

# BreakPilot Integration Tests
# Testet API-Endpoints mit curl
# Voraussetzung: docker-compose up -d

set -e

# Farben für Output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Basis-URLs
CONSENT_SERVICE_URL="http://localhost:8081"
BACKEND_URL="http://localhost:8000"
MAILPIT_URL="http://localhost:8025"

# Test Counter
TESTS_PASSED=0
TESTS_FAILED=0

# Helper Functions
log_info() {
    echo -e "${YELLOW}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[✓]${NC} $1"
    ((TESTS_PASSED++))
}

log_error() {
    echo -e "${RED}[✗]${NC} $1"
    ((TESTS_FAILED++))
}

# Test Helper
test_endpoint() {
    local name=$1
    local method=$2
    local url=$3
    local expected_status=$4
    local headers=$5
    local body=$6

    log_info "Testing: $name"

    if [ -z "$body" ]; then
        response=$(curl -s -w "\n%{http_code}" -X "$method" "$url" $headers)
    else
        response=$(curl -s -w "\n%{http_code}" -X "$method" "$url" $headers -d "$body")
    fi

    http_code=$(echo "$response" | tail -n1)
    response_body=$(echo "$response" | sed '$d')

    if [ "$http_code" == "$expected_status" ]; then
        log_success "$name - Status: $http_code"
    else
        log_error "$name - Expected: $expected_status, Got: $http_code"
        echo "Response: $response_body"
    fi
}

echo "========================================="
echo "BreakPilot Integration Tests"
echo "========================================="
echo ""

# 1. Health Checks
log_info "=== 1. Health Checks ==="

test_endpoint \
    "Consent Service Health" \
    "GET" \
    "$CONSENT_SERVICE_URL/health" \
    "200"

test_endpoint \
    "Backend Health" \
    "GET" \
    "$BACKEND_URL/health" \
    "200"

test_endpoint \
    "Mailpit Health" \
    "GET" \
    "$MAILPIT_URL/api/v1/info" \
    "200"

echo ""

# 2. Auth Tests
log_info "=== 2. Authentication Tests ==="

# Register User
log_info "Registering test user..."
REGISTER_RESPONSE=$(curl -s -X POST "$CONSENT_SERVICE_URL/api/v1/auth/register" \
    -H "Content-Type: application/json" \
    -d '{
        "email": "integration-test@example.com",
        "password": "TestPassword123!",
        "first_name": "Integration",
        "last_name": "Test"
    }' -w "\n%{http_code}")

REGISTER_STATUS=$(echo "$REGISTER_RESPONSE" | tail -n1)
if [ "$REGISTER_STATUS" == "201" ] || [ "$REGISTER_STATUS" == "409" ]; then
    log_success "User Registration (or already exists)"
else
    log_error "User Registration - Status: $REGISTER_STATUS"
fi

# Login
log_info "Logging in..."
LOGIN_RESPONSE=$(curl -s -X POST "$CONSENT_SERVICE_URL/api/v1/auth/login" \
    -H "Content-Type: application/json" \
    -d '{
        "email": "integration-test@example.com",
        "password": "TestPassword123!"
    }')

ACCESS_TOKEN=$(echo "$LOGIN_RESPONSE" | jq -r '.access_token // empty')

if [ -n "$ACCESS_TOKEN" ]; then
    log_success "Login - Token received"
else
    log_error "Login - No access token received"
    echo "Response: $LOGIN_RESPONSE"
fi

echo ""

# 3. Protected Endpoints
log_info "=== 3. Protected Endpoint Tests ==="

if [ -n "$ACCESS_TOKEN" ]; then
    test_endpoint \
        "Get My Consents (Protected)" \
        "GET" \
        "$CONSENT_SERVICE_URL/api/v1/consent/my" \
        "200" \
        "-H 'Authorization: Bearer $ACCESS_TOKEN'"

    test_endpoint \
        "Get My Profile (Protected)" \
        "GET" \
        "$CONSENT_SERVICE_URL/api/v1/users/me" \
        "200" \
        "-H 'Authorization: Bearer $ACCESS_TOKEN'"
else
    log_error "Skipping protected endpoint tests - no access token"
fi

echo ""

# 4. Document Tests
log_info "=== 4. Document Tests ==="

test_endpoint \
    "Get Published Documents" \
    "GET" \
    "$CONSENT_SERVICE_URL/api/v1/documents/published" \
    "200"

test_endpoint \
    "Get Document by Type (terms)" \
    "GET" \
    "$CONSENT_SERVICE_URL/api/v1/documents/type/terms" \
    "200"

echo ""

# 5. Consent Tests
log_info "=== 5. Consent Tests ==="

if [ -n "$ACCESS_TOKEN" ]; then
    # Get published document ID
    DOCUMENTS_RESPONSE=$(curl -s "$CONSENT_SERVICE_URL/api/v1/documents/published")
    VERSION_ID=$(echo "$DOCUMENTS_RESPONSE" | jq -r '.[0].current_version.id // empty')

    if [ -n "$VERSION_ID" ]; then
        log_info "Creating consent for version: $VERSION_ID"

        test_endpoint \
            "Create Consent" \
            "POST" \
            "$CONSENT_SERVICE_URL/api/v1/consent" \
            "201" \
            "-H 'Authorization: Bearer $ACCESS_TOKEN' -H 'Content-Type: application/json'" \
            "{\"document_type\":\"terms\",\"version_id\":\"$VERSION_ID\",\"consented\":true}"

        test_endpoint \
            "Check Consent Status" \
            "GET" \
            "$CONSENT_SERVICE_URL/api/v1/consent/check/terms" \
            "200" \
            "-H 'Authorization: Bearer $ACCESS_TOKEN'"
    else
        log_error "No published document version found for consent test"
    fi
else
    log_error "Skipping consent tests - no access token"
fi

echo ""

# 6. GDPR Tests
log_info "=== 6. GDPR Tests ==="

if [ -n "$ACCESS_TOKEN" ]; then
    test_endpoint \
        "Request Data Export" \
        "POST" \
        "$CONSENT_SERVICE_URL/api/v1/gdpr/export-request" \
        "201" \
        "-H 'Authorization: Bearer $ACCESS_TOKEN'"

    test_endpoint \
        "Get Export Status" \
        "GET" \
        "$CONSENT_SERVICE_URL/api/v1/gdpr/export-status" \
        "200" \
        "-H 'Authorization: Bearer $ACCESS_TOKEN'"
else
    log_error "Skipping GDPR tests - no access token"
fi

echo ""

# 7. Mailpit Tests
log_info "=== 7. Email Tests ==="

# Check for emails in Mailpit
MAILPIT_MESSAGES=$(curl -s "$MAILPIT_URL/api/v1/messages")
MESSAGE_COUNT=$(echo "$MAILPIT_MESSAGES" | jq '.total // 0')

log_info "Emails in Mailpit: $MESSAGE_COUNT"

if [ "$MESSAGE_COUNT" -gt 0 ]; then
    log_success "Emails received in Mailpit"

    # Check for welcome email
    WELCOME_EMAIL=$(echo "$MAILPIT_MESSAGES" | jq '.messages[] | select(.Subject | contains("Willkommen")) | .Subject')
    if [ -n "$WELCOME_EMAIL" ]; then
        log_success "Welcome email found: $WELCOME_EMAIL"
    else
        log_info "No welcome email found (may have been sent in previous run)"
    fi
else
    log_info "No emails in Mailpit (expected if user was already registered)"
fi

echo ""

# 8. DSMS Tests (optional - if DSMS is running)
log_info "=== 8. DSMS Tests (Optional) ==="

if curl -sf "$CONSENT_SERVICE_URL/api/v1/dsms/health" > /dev/null 2>&1; then
    test_endpoint \
        "DSMS Gateway Health" \
        "GET" \
        "$CONSENT_SERVICE_URL/api/v1/dsms/health" \
        "200"
else
    log_info "DSMS not available - skipping DSMS tests"
fi

echo ""

# Summary
echo "========================================="
echo "Test Results"
echo "========================================="
echo -e "${GREEN}Passed:${NC} $TESTS_PASSED"
echo -e "${RED}Failed:${NC} $TESTS_FAILED"
echo "========================================="

if [ $TESTS_FAILED -eq 0 ]; then
    echo -e "${GREEN}All tests passed! ✓${NC}"
    exit 0
else
    echo -e "${RED}Some tests failed! ✗${NC}"
    exit 1
fi
