name: Integration tests

on:
  pull_request:
    types: [opened, synchronize, reopened]
    branches: [master, main]

# Read more about customization: https://toptal-core.atlassian.net/l/c/91SzvPoU#Generated-IT-Workflow
env:
  PARALLEL_MATRIX: |
    [
      {
        "pkg": "@toptal/my-package",
        "location": "packages/my-package",
        "parallelGroups": 3
      }
    ]
  PRINT_COVERAGE: true
  COVERAGE_REPORT_DIR: coverage
  COMMAND: test:integration:ci

  NPM_TOKEN: ${{ secrets.NPM_TOKEN_READ_ONLY }}
  GITHUB_TOKEN: ${{ secrets.TOPTAL_DEVBOT_TOKEN }}

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  create_matrix:
    name: Create:Matrix
    runs-on: ubuntu-latest
    steps:
      - name: Checkout project
        uses: actions/checkout@v3

      - name: Run Matrix
        id: set-matrix
        uses: toptal/davinci-github-actions/create-matrix@v20.0.0
        with:
          parallel-matrix: ${{ env.PARALLEL_MATRIX }}

    outputs:
      matrix: ${{ steps.set-matrix.outputs.matrix }}

  integration_check:
    name: Check:IntegrationTests
    runs-on: ubuntu-latest
    needs: [create_matrix]
    strategy:
      fail-fast: false
      matrix:
        include: ${{ fromJson(needs.create_matrix.outputs.matrix) }}
    env:
      GROUP_INDEX: ${{ matrix.index }}
      GROUP_LOCATION: ${{ matrix.location }}
      GROUP_PACKAGE: ${{ matrix.pkg }}
      PARALLEL_GROUPS: ${{ matrix.total }}
    steps:
      - name: Checkout project
        uses: actions/checkout@v3

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: 20

      - uses: toptal/davinci-github-actions/pnpm-install@v20.0.0

      - uses: toptal/davinci-github-actions/integration-tests@v20.0.0
        with:
          command: workspace ${{ env.GROUP_PACKAGE }} ${{ env.COMMAND }}

      - name: Move coverage output to joint folder
        if: ${{ env.PRINT_COVERAGE == 'true' }}
        run: |
          mkdir integration-coverage
          mv $GROUP_LOCATION/$COVERAGE_REPORT_DIR/coverage-final.json integration-coverage/coverage.${GROUP_PACKAGE////-}.$GROUP_INDEX.json

      - name: Upload Coverage
        if: ${{ env.PRINT_COVERAGE == 'true' }}
        uses: actions/upload-artifact@v3
        with:
          name: integration-coverage
          path: integration-coverage

  coverage_report:
    name: Report:Coverage
    runs-on: ubuntu-latest
    needs: integration_check
    steps:
      - name: Download Coverage
        if: ${{ env.PRINT_COVERAGE == 'true' }}
        uses: actions/download-artifact@v3
        with:
          name: integration-coverage
          path: code-coverage

      - name: Print Coverage
        if: ${{ env.PRINT_COVERAGE == 'true' }}
        uses: toptal/davinci-github-actions/report-coverage@v20.0.0
        with:
          path: code-coverage
          reporter: text-summary
