name: SonarQube Analysis

on:
  push:
    branches:
      - '*'

jobs:
  build:
    name: Build and analyze
    runs-on: ubuntu-latest
    timeout-minutes: 20

    steps:
      - name: Set up JDK 17
        uses: actions/setup-java@v4
        with:
          java-version: 17
          distribution: 'zulu' # Alternative distribution options are available.

      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Shallow clones should be disabled for a better relevancy of analysis

      - name: Setup .NET
        uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '8.0.x' # .NET 8 SDK supports building .NET Framework 4.7.2 projects

      - name: Install SonarQube Cloud scanner
        run: |
          mkdir -p ~/.sonar/scanner
          dotnet tool install dotnet-sonarscanner --tool-path ~/.sonar/scanner

      - name: Restore dependencies
        run: dotnet restore AIImages.sln --verbosity normal

      - name: Build and analyze
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
        run: |
          echo "Starting SonarQube analysis..."
          echo "Current directory: $(pwd)"
          echo "Listing files:"
          ls -la
          echo "Starting SonarQube scanner..."
          
          ~/.sonar/scanner/dotnet-sonarscanner begin \
            /k:"AIImages" \
            /d:sonar.token="${{ secrets.SONAR_TOKEN }}" \
            /d:sonar.host.url="${{ secrets.SONAR_HOST_URL }}" \
            /d:sonar.projectBaseDir="$(pwd)" \
            /d:sonar.cs.opencover.reportsPaths="**/coverage.opencover.xml" \
            /d:sonar.coverage.exclusions="**/obj/**,**/bin/**,**/Assemblies/**" \
            /d:sonar.exclusions="**/obj/**,**/bin/**,**/Assemblies/**,**/Migrations/**" \
            /d:sonar.cpd.exclusions="**/obj/**,**/bin/**" \
            /d:sonar.test.inclusions="**/*Tests.cs,**/*Test.cs" \
            /d:sonar.sources="Source" \
            /d:sonar.sourceEncoding=UTF-8

          echo "Building solution..."
          dotnet build AIImages.sln --verbosity normal --no-incremental -c Release

          echo "Running tests with coverage (if any)..."
          dotnet test AIImages.sln /p:CollectCoverage=true /p:CoverletOutputFormat=opencover /p:CoverletOutput=./coverage/ /p:Exclude="[*.Tests]*" || echo "No tests found, skipping test execution"

          echo "Ending SonarQube analysis..."
          ~/.sonar/scanner/dotnet-sonarscanner end /d:sonar.token="${{ secrets.SONAR_TOKEN }}"

