name: Cache Integration Tests

on:
  pull_request:
    branches:
      - main
      - dev
      - release/*
    paths:
      - 'packages/api/src/cache/**'
      - 'packages/api/src/cluster/**'
      - 'packages/api/src/mcp/**'
      - 'redis-config/**'
      - '.github/workflows/cache-integration-tests.yml'

jobs:
  cache_integration_tests:
    name: Integration Tests that use actual Redis Cache
    timeout-minutes: 30
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Use Node.js 20.x
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'npm'

      - name: Install Redis tools
        run: |
          sudo apt-get update
          sudo apt-get install -y redis-server redis-tools

      - name: Start Single Redis Instance
        run: |
          redis-server --daemonize yes --port 6379
          sleep 2
          # Verify single Redis is running
          redis-cli -p 6379 ping || exit 1

      - name: Start Redis Cluster
        working-directory: redis-config
        run: |
          chmod +x start-cluster.sh stop-cluster.sh
          ./start-cluster.sh
          sleep 10
          # Verify cluster is running
          redis-cli -p 7001 cluster info || exit 1
          redis-cli -p 7002 cluster info || exit 1
          redis-cli -p 7003 cluster info || exit 1

      - name: Install dependencies
        run: npm ci

      - name: Build packages
        run: |
          npm run build:data-provider
          npm run build:data-schemas
          npm run build:api

      - name: Run all cache integration tests (Single Redis Node)
        working-directory: packages/api
        env:
          NODE_ENV: test
          USE_REDIS: true
          USE_REDIS_CLUSTER: false
          REDIS_URI: redis://127.0.0.1:6379
        run: npm run test:cache-integration

      - name: Run all cache integration tests (Redis Cluster)
        working-directory: packages/api
        env:
          NODE_ENV: test
          USE_REDIS: true
          USE_REDIS_CLUSTER: true
          REDIS_URI: redis://127.0.0.1:7001,redis://127.0.0.1:7002,redis://127.0.0.1:7003
        run: npm run test:cache-integration

      - name: Stop Redis Cluster
        if: always()
        working-directory: redis-config
        run: ./stop-cluster.sh || true

      - name: Stop Single Redis Instance
        if: always()
        run: redis-cli -p 6379 shutdown || true