on:
  push:
    # branches:
      # - main
      # - development
  pull_request:
      types: [opened, synchronize, reopened]

name: SonarQube Scan
jobs:
  sonarqube:
    name: SonarQube Trigger
    runs-on: ubuntu-latest
    steps:
    - name: Checking out
      uses: actions/checkout@v4
      with:
        fetch-depth: 0

    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.11'

    - name: Install dependencies
      run: |
        pip install -r requirements.txt

    - name: Run tests with coverage
      run: |
        coverage run --source='.' manage.py test
        coverage xml

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

    - name: Cache SonarQube packages
      uses: actions/cache@v3
      with:
        path: ~/.sonar/cache
        key: ${{ runner.os }}-sonar
        restore-keys: ${{ runner.os }}-sonar

    - name: Download and setup SonarScanner
      run: |
        mkdir -p $HOME/.sonar
        wget -q https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-5.0.1.3006-linux.zip
        unzip -q sonar-scanner-cli-5.0.1.3006-linux.zip -d $HOME/.sonar/
        echo "$HOME/.sonar/sonar-scanner-5.0.1.3006-linux/bin" >> $GITHUB_PATH

    - name: Verify Java version
      run: java -version

    - name: SonarQube Scan
      env:
        SONAR_HOST_URL: ${{ secrets.SONARQUBE_HOST }}
        SONAR_TOKEN: ${{ secrets.SONARQUBE_TOKEN }}
      run: |
        sonar-scanner \
          -Dsonar.projectKey=${{ github.event.repository.name }} \
          -Dsonar.sources=. \
          -Dsonar.host.url=${SONAR_HOST_URL} \
          -Dsonar.token=${SONAR_TOKEN} \
          -Dsonar.python.coverage.reportPaths=coverage.xml
