name: Run API tests

on:
  workflow_dispatch:
  repository_dispatch:
    types: [api_tests_workflow]

concurrency:
  group: ci-api-tests
  cancel-in-progress: false

permissions:
  contents: write
  checks: write
  pull-requests: write

jobs:
  api-tests:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.client_payload.ref || github.ref }}
      - name: Print current branch value
        run: |
          echo "The ref value is: ${{ github.event.client_payload.ref || github.ref }}"
      - name: Set up Python 3.10
        uses: actions/setup-python@v5
        with:
          python-version: "3.10"
          cache: "pip"
      - name: Prepare artifact name
        run: |
          raw_branch="${GITHUB_REF#refs/heads/}"
          sanitized_branch="${raw_branch//\//-}"
          sanitized_branch="${sanitized_branch//[^A-Za-z0-9._-]/-}"
          SHORT_BRANCH="${sanitized_branch:0:20}"
          TIMESTAMP=$(date +'%Y%m%d-%H%M%S')
          echo "SHORT_BRANCH=$SHORT_BRANCH" >> $GITHUB_ENV
          echo "TIMESTAMP=$TIMESTAMP"   >> $GITHUB_ENV
      - name: Run tests
        env:
          DKU_DSS_URL: ${{ secrets.tests_integrations_url }}
          DKU_API_KEY: ${{ secrets.tests_integrations_api_key }}
          DSS_USERNAME: ${{ secrets.e2e_user_name }}
          DSS_PASSWORD: ${{ secrets.e2e_password }}
        run: |
          python -m pip install --upgrade pip
          cd tests/api_tests
          pip install -r requirements.txt
          playwright install chromium
          TMPDIR=/tmp/ make tests-parallel
      - name: Zip tests results
        if: always()
        run: |
          echo "Zipping tests results"
          pwd
          zip -r out.zip tests-out
      - name: Upload test results to workflow artifacts
        uses: actions/upload-artifact@v4
        if: always()
        with:
          name: api-tests-${{ env.SHORT_BRANCH }}-${{ env.TIMESTAMP }}
          path: out.zip
          retention-days: 1
      - name: Post API Tests status to PR
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          STATUS="success"
          DESCRIPTION="API tests completed successfully"

          if [ "${{ job.status }}" != "success" ]; then
            STATUS="failure"
            DESCRIPTION="API tests failed"
          fi

          # Get the SHA of the commit for the current HEAD
          GITHUB_SHA=$(git rev-parse HEAD)
          
          # Post the status to GitHub
          curl -X POST -H "Authorization: token $GITHUB_TOKEN" \
            -H "Accept: application/vnd.github.v3+json" \
            https://api.github.com/repos/${{ github.repository }}/statuses/$GITHUB_SHA \
            -d "{\"state\": \"$STATUS\", \"context\": \"API Tests\", \"description\": \"$DESCRIPTION\"}"
