name: Run Playwright Tests
on:
  workflow_dispatch:
  repository_dispatch:
    types: [playwright_workflow]
jobs:
  test:
    timeout-minutes: 60
    runs-on: macos-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 }}"
      - uses: actions/setup-node@v4
        with:
          node-version: lts/*
      - name: Install dependencies
        run: npm ci
      - name: Install Playwright Browsers
        run: npx playwright install --with-deps
      - 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 Playwright tests
        env:
          STAGING: 1
          E2E_LOGIN_URL: "${{ secrets.tests_integrations_url}}public-webapps/TESTINTEGRATIONPORTALPLUGIN/1dFpV4r/new"
          E2E_AUTH_URL: "${{ secrets.tests_integrations_url}}webapps/TESTINTEGRATIONPORTALPLUGIN/1dFpV4r/new"
          E2E_USER_NAME: ${{ secrets.e2e_user_name }}
          E2E_PASSWORD: ${{ secrets.e2e_password }}
        run: npx playwright test
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: playwright-artifacts-${{ env.SHORT_BRANCH }}-${{ env.TIMESTAMP }}
          path: playwright-report/
          retention-days: 1
      - name: Post Playwright Tests status to PR
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          STATUS="success"
          DESCRIPTION="Playwright tests completed successfully"

          if [ "${{ job.status }}" != "success" ]; then
            STATUS="failure"
            DESCRIPTION="Playwright 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\": \"Playwright Tests\", \"description\": \"$DESCRIPTION\"}"

