name: SonarQube Analysis

on:
  schedule:
    - cron: '0 3 * * *'
  workflow_dispatch:

jobs:
  sonarqube:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - uses: actions/setup-node@v4
        with:
          node-version: 22

      - name: Install dependencies
        run: npm ci

      - name: Run tests with coverage
        run: npx vitest run --exclude 'e2e/**' --coverage --coverage.reporter=lcov

      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: 17

      - name: Install sonar-scanner
        run: |
          SONAR_SCANNER_VERSION=6.2.1.4610
          ARCH=$(uname -m)
          if [ "$ARCH" = "aarch64" ] || [ "$ARCH" = "arm64" ]; then
            PLATFORM="linux-aarch64"
          else
            PLATFORM="linux-x64"
          fi
          curl -sSLo sonar-scanner.zip "https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-${SONAR_SCANNER_VERSION}-${PLATFORM}.zip"
          unzip -q sonar-scanner.zip
          echo "$PWD/sonar-scanner-${SONAR_SCANNER_VERSION}-${PLATFORM}/bin" >> "$GITHUB_PATH"

      - name: Run SonarQube analysis
        env:
          SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
        run: |
          if [ -z "$SONAR_HOST_URL" ] || ! echo "$SONAR_HOST_URL" | grep -qE '^https?://'; then
            echo "::error::SONAR_HOST_URL is missing or invalid (got: '$SONAR_HOST_URL'). Set it as a repo variable with full URL (e.g. https://sonar.example.com)."
            exit 1
          fi
          sonar-scanner \
            -Dsonar.host.url="$SONAR_HOST_URL" \
            -Dsonar.login="$SONAR_TOKEN" \
            -Dsonar.projectKey=cameleer-design-system \
            -Dsonar.projectName="Cameleer Design System" \
            -Dsonar.sources=src/design-system \
            -Dsonar.tests=src/design-system \
            -Dsonar.test.inclusions="**/*.test.tsx,**/*.test.ts" \
            -Dsonar.javascript.lcov.reportPaths=coverage/lcov.info \
            -Dsonar.exclusions="**/node_modules/**,**/dist/**"
