name: CI

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up JDK 21
        uses: actions/setup-java@v4
        with:
          java-version: '21'
          distribution: 'temurin'

      - name: Cache Gradle packages
        uses: actions/cache@v4
        with:
          path: |
            ~/.gradle/caches
            ~/.gradle/wrapper
          key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
          restore-keys: ${{ runner.os }}-gradle

      - name: Generate Gradle wrapper if missing
        run: |
          if [ ! -f "./gradlew" ]; then
            echo "Gradle wrapper missing. Generating..."
            gradle wrapper --gradle-version 8.10
          fi
          chmod +x gradlew

      - name: Run Ktlint
        run: ./gradlew ktlintCheck

      - name: Run Detekt
        if: always()
        run: ./gradlew detekt

      - name: Build and run tests
        if: always()
        run: ./gradlew build test jacocoTestReport

      - name: Upload coverage to Codecov
        if: success()
        uses: codecov/codecov-action@v4
        with:
          token: ${{ secrets.CODECOV_TOKEN }}
          files: build/reports/jacoco/test/jacocoTestReport.xml
          fail_ci_if_error: false

      - name: Upload coverage to DeepSource
        if: always() # always run even if the previous step fails
        env:
          DEEPSOURCE_DSN: ${{ secrets.DEEPSOURCE_DSN }}
        run: |
          # Tests have finished and a test coverage report is available
          # Install deepsource CLI
            curl https://deepsource.io/cli | sh
          # From the root directory, run the report coverage command
            ./bin/deepsource report --analyzer test-coverage --key kotlin --value-file build/reports/jacoco/test/jacocoTestReport.xml
