# Integration Tests Pipeline
# Separate Datei weil Services auf Pipeline-Ebene definiert werden muessen
#
# Diese Pipeline laeuft parallel zur main.yml und testet:
# - Database Connectivity (PostgreSQL)
# - Cache Connectivity (Valkey/Redis)
# - Service-to-Service Kommunikation
#
# Dokumentation: docs/testing/integration-test-environment.md

when:
  - event: [push, pull_request]
    branch: [main, develop]

clone:
  git:
    image: woodpeckerci/plugin-git
    settings:
      depth: 1
    extra_hosts:
      - macmini:192.168.178.100

# Services auf Pipeline-Ebene (NICHT Step-Ebene!)
# Diese Services sind fuer ALLE Steps verfuegbar
services:
  postgres:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: breakpilot
      POSTGRES_PASSWORD: breakpilot_test
      POSTGRES_DB: breakpilot_test

  valkey:
    image: valkey/valkey:8-alpine

steps:
  wait-for-services:
    image: postgres:16-alpine
    commands:
      - |
        echo "=== Waiting for PostgreSQL ==="
        for i in $(seq 1 30); do
          if pg_isready -h postgres -U breakpilot; then
            echo "PostgreSQL ready after $i attempts!"
            break
          fi
          echo "Attempt $i/30: PostgreSQL not ready, waiting..."
          sleep 2
        done
        # Final check
        if ! pg_isready -h postgres -U breakpilot; then
          echo "ERROR: PostgreSQL not ready after 30 attempts"
          exit 1
        fi
      - |
        echo "=== Waiting for Valkey ==="
        # Install redis-cli in postgres alpine image
        apk add --no-cache redis > /dev/null 2>&1 || true
        for i in $(seq 1 30); do
          if redis-cli -h valkey ping 2>/dev/null | grep -q PONG; then
            echo "Valkey ready after $i attempts!"
            break
          fi
          echo "Attempt $i/30: Valkey not ready, waiting..."
          sleep 2
        done
        # Final check
        if ! redis-cli -h valkey ping 2>/dev/null | grep -q PONG; then
          echo "ERROR: Valkey not ready after 30 attempts"
          exit 1
        fi
      - echo "=== All services ready ==="

  integration-tests:
    image: breakpilot/python-ci:3.12
    environment:
      CI: "true"
      DATABASE_URL: postgresql://breakpilot:breakpilot_test@postgres:5432/breakpilot_test
      VALKEY_URL: redis://valkey:6379
      REDIS_URL: redis://valkey:6379
      SKIP_INTEGRATION_TESTS: "false"
      SKIP_DB_TESTS: "false"
      SKIP_WEASYPRINT_TESTS: "false"
      # Test-spezifische Umgebungsvariablen
      ENVIRONMENT: "testing"
      JWT_SECRET: "test-secret-key-for-integration-tests"
      TEACHER_REQUIRE_AUTH: "false"
      GAME_USE_DATABASE: "false"
    commands:
      - |
        set -uo pipefail
        mkdir -p .ci-results
        cd backend

        # PYTHONPATH setzen damit lokale Module gefunden werden
        export PYTHONPATH="$(pwd):${PYTHONPATH:-}"

        echo "=== Installing dependencies ==="
        pip install --quiet --no-cache-dir -r requirements.txt

        echo "=== Running Integration Tests ==="
        set +e
        python -m pytest tests/test_integration/ -v \
          --tb=short \
          --json-report \
          --json-report-file=../.ci-results/test-integration.json
        TEST_EXIT=$?
        set -e

        # Ergebnisse auswerten
        if [ -f ../.ci-results/test-integration.json ]; then
          TOTAL=$(python3 -c "import json; d=json.load(open('../.ci-results/test-integration.json')); print(d.get('summary',{}).get('total',0))" 2>/dev/null || echo "0")
          PASSED=$(python3 -c "import json; d=json.load(open('../.ci-results/test-integration.json')); print(d.get('summary',{}).get('passed',0))" 2>/dev/null || echo "0")
          FAILED=$(python3 -c "import json; d=json.load(open('../.ci-results/test-integration.json')); print(d.get('summary',{}).get('failed',0))" 2>/dev/null || echo "0")
          SKIPPED=$(python3 -c "import json; d=json.load(open('../.ci-results/test-integration.json')); print(d.get('summary',{}).get('skipped',0))" 2>/dev/null || echo "0")
        else
          echo "WARNUNG: Keine JSON-Ergebnisse gefunden"
          TOTAL=0; PASSED=0; FAILED=0; SKIPPED=0
        fi

        echo "{\"service\":\"integration-tests\",\"framework\":\"pytest\",\"total\":$TOTAL,\"passed\":$PASSED,\"failed\":$FAILED,\"skipped\":$SKIPPED,\"coverage\":0}" > ../.ci-results/results-integration.json
        cat ../.ci-results/results-integration.json

        echo ""
        echo "=== Integration Test Summary ==="
        echo "Total: $TOTAL | Passed: $PASSED | Failed: $FAILED | Skipped: $SKIPPED"

        if [ "$TEST_EXIT" -ne "0" ]; then
          echo "Integration tests failed with exit code $TEST_EXIT"
          exit 1
        fi
    depends_on:
      - wait-for-services

  report-integration-results:
    image: curlimages/curl:8.10.1
    commands:
      - |
        set -uo pipefail
        echo "=== Sende Integration Test-Ergebnisse an Dashboard ==="

        if [ -f .ci-results/results-integration.json ]; then
          echo "Sending integration test results..."
          curl -f -sS -X POST "http://backend:8000/api/tests/ci-result" \
            -H "Content-Type: application/json" \
            -d "{
              \"pipeline_id\": \"${CI_PIPELINE_NUMBER}\",
              \"commit\": \"${CI_COMMIT_SHA}\",
              \"branch\": \"${CI_COMMIT_BRANCH}\",
              \"status\": \"${CI_PIPELINE_STATUS:-unknown}\",
              \"test_results\": $(cat .ci-results/results-integration.json)
            }" || echo "WARNUNG: Konnte Ergebnisse nicht an Dashboard senden"
        else
          echo "Keine Integration-Ergebnisse zum Senden gefunden"
        fi

        echo "=== Integration Test-Ergebnisse gesendet ==="
    when:
      status: [success, failure]
    depends_on:
      - integration-tests
