name: PR Checks

on:
  pull_request:
    branches:
      - main

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

      - name: Setup .NET
        uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '10.0.x'

      - name: Restore dependencies
        run: dotnet restore

      - name: Verify Trivy dependency scan inputs
        run: |
          lock_count="$(find . -name packages.lock.json -not -path "*/bin/*" -not -path "*/obj/*" | tee trivy-targets.txt | wc -l)"
          echo "Trivy NuGet lock files: ${lock_count}"
          if [ "${lock_count}" -eq 0 ]; then
            echo "::error::No packages.lock.json files found. Trivy would scan 0 NuGet dependency files."
            exit 1
          fi

      # ── Linting ──

      - name: Lint C# code style
        run: dotnet format --verify-no-changes --verbosity diagnostic

      # ── Security ──

      - name: Check NuGet packages for vulnerabilities
        run: |
          dotnet list package --vulnerable --include-transitive 2>&1 | tee nuget-audit.txt
          if grep -qi "has the following vulnerable packages" nuget-audit.txt; then
            echo "::error::Vulnerable NuGet packages found!"
            exit 1
          fi
          echo "No vulnerable packages detected."

      - name: Install Trivy
        run: |
          curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh | sh -s -- -b /usr/local/bin
          trivy --version

      - name: Trivy filesystem security scan
        run: |
          set +e
          trivy fs --scanners vuln,misconfig,secret --exit-code 1 --severity HIGH,CRITICAL . 2>&1 | tee trivy-scan.log
          trivy_exit="${PIPESTATUS[0]}"
          if ! grep -Eq "Number of language-specific files[[:space:]]+num=[1-9][0-9]*" trivy-scan.log; then
            echo "::error::Trivy did not detect any language-specific dependency files."
            exit 1
          fi
          exit "${trivy_exit}"

      # ── Build (includes SAST via SecurityCodeScan Roslyn analyzer) ──

      - name: Build Shared
        run: dotnet build src/GmRelay.Shared/GmRelay.Shared.csproj --no-restore

      - name: Build Bot (compile check, includes SAST)
        run: dotnet build src/GmRelay.Bot/GmRelay.Bot.csproj --no-restore

      - name: Build Discord Bot (compile check, includes SAST)
        run: dotnet build src/GmRelay.DiscordBot/GmRelay.DiscordBot.csproj --no-restore

      - name: Build Web (compile check, includes SAST)
        run: dotnet build src/GmRelay.Web/GmRelay.Web.csproj --no-restore

      # ── Tests ──

      - name: Run tests
        run: dotnet test tests/GmRelay.Bot.Tests/GmRelay.Bot.Tests.csproj --verbosity normal
