name: Backend Integration Tests
on:
  push:
    paths:
      - 'meet-ce/backend/src/**'
      - 'meet-ce/backend/package.json'
      - 'pnpm-lock.yaml'
      - 'meet-ce/backend/tests/**'
      - '.github/workflows/backend-integration-test.yaml'
  pull_request:
    paths:
      - 'meet-ce/backend/src/**'
  workflow_dispatch:
    inputs:
      use-aws:
        description: 'Run recording tests in AWS EC2 runner'
        default: 'true'
      aws-instance-type:
        description: 'AWS EC2 instance type'
        default: 'c5.2xlarge'

jobs:
  build-components:
    name: Build OpenVidu Components Angular
    runs-on: ${{ vars.LABEL_WORKER_SELFHOSTED }}
    steps:
      - name: Build Components
        id: build
        uses: OpenVidu/actions/build-openvidu-components-angular@main
    outputs:
      artifact_name: ${{ steps.build.outputs.artifact_name }}

  test-api:
    name: ${{ matrix.test-name }}
    needs: build-components
    runs-on: ${{ vars.LABEL_WORKER_SELFHOSTED }}
    strategy:
      fail-fast: false
      matrix:
        include:
          - test-name: 'Room Management API Tests (Rooms, Meetings)'
            test-script: 'test:integration-backend-room-management'
          - test-name: 'Webhook Tests'
            test-script: 'test:integration-backend-webhooks'
          - test-name: 'Auth & Security API Tests (Security, Auth, API Keys, Users)'
            test-script: 'test:integration-backend-auth-security'
          - test-name: 'Config & Analytics API Tests (Global Config, Analytics)'
            test-script: 'test:integration-backend-config-analytics'
    steps:
      - name: Install LK CLI
        run: curl -sSL https://get.livekit.io/cli | bash

      - name: Setup Node.js
        uses: actions/setup-node@v5
        with:
          node-version: '22.13'
      - name: Setup pnpm
        uses: pnpm/action-setup@v4
        with:
          version: 10.18.3

      - name: Setup OpenVidu Local Deployment
        uses: OpenVidu/actions/start-openvidu-local-deployment@main
        with:
          ref-openvidu-local-deployment: development
          pre_startup_commands: |
            cat <<'BASH' > pre_startup_commands.sh
            #!/bin/bash
            echo "Commenting out openvidu-meet container in docker-compose.yaml"
            if [ -f docker-compose.yaml ]; then
              yq e 'del(.services.openvidu-meet)' -i docker-compose.yaml
            fi
            BASH
            chmod +x pre_startup_commands.sh && ./pre_startup_commands.sh

      - name: Setup OpenVidu Meet
        uses: OpenVidu/actions/start-openvidu-meet@main
        with:
          build_components_angular: 'true'
          components_artifact_name: ${{ needs.build-components.outputs.artifact_name }}

      - name: Run tests
        run: pnpm run ${{ matrix.test-script }}
        env:
          JEST_JUNIT_OUTPUT_DIR: './meet-ce/backend/reports/'

      - name: Upload OpenVidu Meet logs
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: ${{ matrix.test-name }}-openvidu-meet-logs
          path: meet_backend.log
          retention-days: 2

      - name: Publish Test Report
        uses: mikepenz/action-junit-report@v4
        if: always()
        with:
          report_paths: '**/reports/junit.xml'
          fail_on_failure: true
          require_tests: true

      - name: Clean up
        if: always()
        uses: OpenVidu/actions/cleanup@main

  start-aws-runner-s3:
    name: Prepare AWS runner (S3)
    runs-on: ${{ vars.LABEL_WORKER_SELFHOSTED }}
    if: ${{ inputs.use-aws != 'false' }}
    outputs:
      label: ${{ steps.start-ec2-runner.outputs.label }}
      ec2-instance-id: ${{ steps.start-ec2-runner.outputs.ec2-instance-id }}
    steps:
      - name: Start AWS EC2 Runner
        id: start-ec2-runner
        uses: OpenVidu/actions/start-aws-runner@main
        with:
          aws-instance-type: ${{ inputs.aws-instance-type || 'c5.2xlarge' }}
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: ${{ vars.AWS_REGION }}
          github-token: ${{ secrets.OPENVIDU_GITHUB_TOKEN }}
          ec2-image-id: ${{ vars.AWS_GITHUB_ACTIONS_AMI }}
          subnet-id: ${{ vars.AWS_SUBNET_ID }}
          security-group-id: ${{ vars.AWS_SECURITY_GROUP_ID }}
          workflow-name: ${{ github.workflow }}-s3
          repository-name: ${{ github.repository }}

  start-aws-runner-abs:
    name: Prepare AWS runner (ABS)
    runs-on: ${{ vars.LABEL_WORKER_SELFHOSTED }}
    if: ${{ inputs.use-aws != 'false' }}
    outputs:
      label: ${{ steps.start-ec2-runner.outputs.label }}
      ec2-instance-id: ${{ steps.start-ec2-runner.outputs.ec2-instance-id }}
    steps:
      - name: Start AWS EC2 Runner
        id: start-ec2-runner
        uses: OpenVidu/actions/start-aws-runner@main
        with:
          aws-instance-type: ${{ inputs.aws-instance-type || 'c5.2xlarge' }}
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: ${{ vars.AWS_REGION }}
          github-token: ${{ secrets.OPENVIDU_GITHUB_TOKEN }}
          ec2-image-id: ${{ vars.AWS_GITHUB_ACTIONS_AMI }}
          subnet-id: ${{ vars.AWS_SUBNET_ID }}
          security-group-id: ${{ vars.AWS_SECURITY_GROUP_ID }}
          workflow-name: ${{ github.workflow }}-abs
          repository-name: ${{ github.repository }}

  start-aws-runner-gcs:
    name: Prepare AWS runner (GCS)
    runs-on: ${{ vars.LABEL_WORKER_SELFHOSTED }}
    if: ${{ inputs.use-aws != 'false' }}
    outputs:
      label: ${{ steps.start-ec2-runner.outputs.label }}
      ec2-instance-id: ${{ steps.start-ec2-runner.outputs.ec2-instance-id }}
    steps:
      - name: Start AWS EC2 Runner
        id: start-ec2-runner
        uses: OpenVidu/actions/start-aws-runner@main
        with:
          aws-instance-type: ${{ inputs.aws-instance-type || 'c5.2xlarge' }}
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: ${{ vars.AWS_REGION }}
          github-token: ${{ secrets.OPENVIDU_GITHUB_TOKEN }}
          ec2-image-id: ${{ vars.AWS_GITHUB_ACTIONS_AMI }}
          subnet-id: ${{ vars.AWS_SUBNET_ID }}
          security-group-id: ${{ vars.AWS_SECURITY_GROUP_ID }}
          workflow-name: ${{ github.workflow }}-gcs
          repository-name: ${{ github.repository }}

  test-recordings:
    name: Recordings API Tests (${{ matrix.storage-provider }})
    needs:
      - start-aws-runner-s3
      - start-aws-runner-abs
      - start-aws-runner-gcs
      - build-components
    if: ${{ always() && (needs.start-aws-runner-s3.result == 'success' || needs.start-aws-runner-s3.result == 'skipped') && (needs.start-aws-runner-abs.result == 'success' || needs.start-aws-runner-abs.result == 'skipped') && (needs.start-aws-runner-gcs.result == 'success' || needs.start-aws-runner-gcs.result == 'skipped') }}
    runs-on: ${{ (matrix.storage-provider == 's3' && needs.start-aws-runner-s3.outputs.label) || (matrix.storage-provider == 'abs' && needs.start-aws-runner-abs.outputs.label) || (matrix.storage-provider == 'gcs' && needs.start-aws-runner-gcs.outputs.label) || vars.LABEL_WORKER_SELFHOSTED }}
    strategy:
      fail-fast: false
      matrix:
        storage-provider: [s3, abs, gcs]
    timeout-minutes: 30
    steps:
      - name: Setup Node.js
        uses: actions/setup-node@v5
        with:
          node-version: '22.13'
      - name: Setup pnpm
        uses: pnpm/action-setup@v2
        with:
          version: 10
      - name: Install LK CLI
        run: curl -sSL https://get.livekit.io/cli | bash
      - name: Save GCP credentials
        if: matrix.storage-provider == 'gcs'
        run: |
          echo '${{ secrets.GCP_CREDENTIALS_JSON }}' > /tmp/credentials.json
          chmod 600 /tmp/credentials.json
      - name: Remove existing rooms or recordings in buckets
        if: matrix.storage-provider == 'abs' || matrix.storage-provider == 'gcs'
        run: |
          if [[ "${{ matrix.storage-provider }}" == "abs" ]]; then
            echo "Installing Azure CLI..."
            curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
            
            echo "Logging into Azure..."
            az storage blob delete-batch \
              --account-name "${{ vars.MEET_AZURE_ACCOUNT_NAME }}" \
              --account-key "${{ secrets.MEET_AZURE_ACCOUNT_KEY }}" \
              --source openvidu-appdata-recordings \
              --pattern "openvidu-meet/*" \
              --delete-snapshots include || echo "No files found to delete or container doesn't exist"
            echo "Existing blobs deleted from Azure Blob Storage container."
              
          elif [[ "${{ matrix.storage-provider }}" == "gcs" ]]; then
            echo "Installing Google Cloud CLI..."
            curl https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-cli-linux-x86_64.tar.gz | tar -xz
            ./google-cloud-sdk/install.sh --quiet
            export PATH=$PATH:$(pwd)/google-cloud-sdk/bin
            
            echo "Authenticating with Google Cloud..."
            gcloud auth activate-service-account --key-file=/tmp/credentials.json
            
            echo "Removing openvidu-meet folder from GCS bucket..."
            gsutil -m rm -r gs://openvidu-appdata/openvidu-meet/ || echo "No files found to delete or bucket doesn't exist"
          fi
      - name: Setup OpenVidu Local Deployment
        uses: OpenVidu/actions/start-openvidu-local-deployment@main
        with:
          ref-openvidu-local-deployment: development
          pre_startup_commands: |
            cat <<'BASH' > pre_startup_commands.sh
            #!/bin/bash
            if [[ "${{ matrix.storage-provider }}" == "abs" ]]; then
              echo "Using Azure Blob Storage provider"
              yq e -i '
                del(.storage.s3) |
                .storage.azure = {
                  "account_name": "${{ vars.MEET_AZURE_ACCOUNT_NAME }}",
                  "account_key": "${{ secrets.MEET_AZURE_ACCOUNT_KEY }}",
                  "container_name": "openvidu-appdata-recordings"
                }
              ' egress.yaml
            elif [[ "${{ matrix.storage-provider }}" == "gcs" ]]; then
              echo "Using Google Cloud Storage provider"
              yq eval --inplace '.storage.gcp.credentials_json = (load("/tmp/credentials.json") | tostring) | .storage.gcp.credentials_json style="single"' egress.yaml

              yq e -i '
                del(.storage.s3) |
                .storage.gcp.bucket = "openvidu-appdata"
              ' egress.yaml
            fi

            echo "Commenting out openvidu-meet container in docker-compose.yaml"
            if [ -f docker-compose.yaml ]; then
              yq e 'del(.services.openvidu-meet)' -i docker-compose.yaml
            fi
            BASH
            chmod +x pre_startup_commands.sh && ./pre_startup_commands.sh

      - name: Setup OpenVidu Meet
        uses: OpenVidu/actions/start-openvidu-meet@main
        with:
          build_components_angular: 'true'
          components_artifact_name: ${{ needs.build-components.outputs.artifact_name }}
        env:
          MEET_BLOB_STORAGE_MODE: ${{ matrix.storage-provider }}
          # ABS variables
          MEET_AZURE_ACCOUNT_NAME: ${{ matrix.storage-provider == 'abs' && vars.MEET_AZURE_ACCOUNT_NAME || '' }}
          MEET_AZURE_ACCOUNT_KEY: ${{ matrix.storage-provider == 'abs' && secrets.MEET_AZURE_ACCOUNT_KEY || '' }}
          MEET_AZURE_CONTAINER_NAME: ${{ matrix.storage-provider == 'abs' && 'openvidu-appdata-recordings' || '' }}
          # GCS variables
          GOOGLE_APPLICATION_CREDENTIALS: ${{ matrix.storage-provider == 'gcs' && '/tmp/credentials.json' || '' }}
          MEET_S3_BUCKET: ${{ matrix.storage-provider == 'gcs' && 'openvidu-appdata' || 'openvidu-appdata' }}

      - name: Run tests
        run: pnpm run test:integration-backend-recordings
        env:
          JEST_JUNIT_OUTPUT_DIR: './meet-ce/backend/reports/'
          MEET_BLOB_STORAGE_MODE: ${{ matrix.storage-provider }}
          # ABS variables
          MEET_AZURE_ACCOUNT_NAME: ${{ matrix.storage-provider == 'abs' && vars.MEET_AZURE_ACCOUNT_NAME || '' }}
          MEET_AZURE_ACCOUNT_KEY: ${{ matrix.storage-provider == 'abs' && secrets.MEET_AZURE_ACCOUNT_KEY || '' }}
          MEET_AZURE_CONTAINER_NAME: ${{ matrix.storage-provider == 'abs' && 'openvidu-appdata-recordings' || '' }}
          # GCS variables
          GOOGLE_APPLICATION_CREDENTIALS: ${{ matrix.storage-provider == 'gcs' && '/tmp/credentials.json' || '' }}
          MEET_S3_BUCKET: ${{ matrix.storage-provider == 'gcs' && 'openvidu-appdata' || 'openvidu-appdata' }}

      - name: Publish Test Report
        uses: mikepenz/action-junit-report@v4
        if: always()
        with:
          report_paths: '**/reports/junit.xml'
          fail_on_failure: true
          require_tests: true

      - name: Upload OpenVidu Meet logs
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: recordings-test-${{ matrix.storage-provider }}-openvidu-meet-logs
          path: meet_backend.log
          retention-days: 2

      - name: Clean up credentials
        if: always() && matrix.storage-provider == 'gcs'
        run: |
          rm -f /tmp/credentials.json
          echo "GCP credentials file removed"

      - name: Clean up
        if: always()
        uses: OpenVidu/actions/cleanup@main

  stop-runner:
    name: Stop EC2 runner (${{ matrix.storage-provider }})
    needs:
      - start-aws-runner-s3
      - start-aws-runner-abs
      - start-aws-runner-gcs
      - test-recordings
    runs-on: ${{ vars.LABEL_WORKER_SELFHOSTED }}
    if: ${{ always() }}
    strategy:
      fail-fast: false
      matrix:
        storage-provider: [s3, abs, gcs]
    steps:
      - name: Stop AWS EC2 Runner
        if: ${{ (matrix.storage-provider == 's3' && needs.start-aws-runner-s3.result != 'skipped') || (matrix.storage-provider == 'abs' && needs.start-aws-runner-abs.result != 'skipped') || (matrix.storage-provider == 'gcs' && needs.start-aws-runner-gcs.result != 'skipped') }}
        uses: OpenVidu/actions/stop-aws-runner@main
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: ${{ vars.AWS_REGION }}
          github-token: ${{ secrets.OPENVIDU_GITHUB_TOKEN }}
          label: ${{ (matrix.storage-provider == 's3' && needs.start-aws-runner-s3.outputs.label) || (matrix.storage-provider == 'abs' && needs.start-aws-runner-abs.outputs.label) || (matrix.storage-provider == 'gcs' && needs.start-aws-runner-gcs.outputs.label) }}
          ec2-instance-id: ${{ (matrix.storage-provider == 's3' && needs.start-aws-runner-s3.outputs.ec2-instance-id) || (matrix.storage-provider == 'abs' && needs.start-aws-runner-abs.outputs.ec2-instance-id) || (matrix.storage-provider == 'gcs' && needs.start-aws-runner-gcs.outputs.ec2-instance-id) }}

  remove-components-artifact:
    name: Remove OpenVidu Components Angular Artifact
    needs:
      - build-components
      - test-api
      - test-recordings
    runs-on: ${{ vars.LABEL_WORKER_SELFHOSTED }}
    if: ${{ always() }}
    steps:
      - name: Remove Artifact
        uses: geekyeggo/delete-artifact@v5
        with:
          name: ${{ needs.build-components.outputs.artifact_name }}
