name: Security Scanning

on:
  schedule:
    - cron: '0 0 * * 0'  # Run weekly on Sunday at midnight
  workflow_dispatch:  # Allow manual triggering

jobs:
  dependency-check:
    name: "Dependency Vulnerability Scan"
    container:
      image: "cimg/openjdk:23.0-node"
    steps:
      - name: "Checkout"
        uses: actions/checkout@v4
      
      - name: "Setup Node.js"
        uses: actions/setup-node@v4
        with:
          node-version: 20
      
      - name: "Install Bun"
        uses: oven-sh/setup-bun@v2
        with:
          bun-version: latest
      
      - name: "Run npm audit (Backend Dependencies)"
        working-directory: ./backend
        continue-on-error: true
        run: |
          npm init -y
          npm audit --json > npm-audit-report.json
          echo "### Backend npm Audit Results" >> $GITHUB_STEP_SUMMARY
          echo "$(npm audit --omit dev | tail -n 5)" >> $GITHUB_STEP_SUMMARY
      
      - name: "Run npm audit (Frontend Dependencies)"
        working-directory: ./frontend
        continue-on-error: true
        run: |
          bun pm audit --json > bun-audit-report.json
          echo "### Frontend bun Audit Results" >> $GITHUB_STEP_SUMMARY
          echo "$(bun pm audit | tail -n 5)" >> $GITHUB_STEP_SUMMARY
      
      - name: "Run OWASP Dependency Check"
        uses: dependency-check/Dependency-Check_Action@main
        with:
          project: "Casino"
          path: "."
          format: "HTML"
          out: "reports"
          args: >
            --failOnCVSS 7
            --enableRetired
      
      - name: "Upload Dependency Check Report"
        uses: actions/upload-artifact@v4
        with:
          name: dependency-check-report
          path: reports/
          retention-days: 30
      
      - name: "Summarize Findings"
        run: |
          echo "### OWASP Dependency Check Summary" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "Full report has been uploaded as an artifact." >> $GITHUB_STEP_SUMMARY
          
          HIGH_VULNS=$(grep -c "High" reports/dependency-check-report.html || echo "0")
          CRITICAL_VULNS=$(grep -c "Critical" reports/dependency-check-report.html || echo "0")
          
          echo "| Severity | Count |" >> $GITHUB_STEP_SUMMARY
          echo "| --- | --- |" >> $GITHUB_STEP_SUMMARY
          echo "| Critical | $CRITICAL_VULNS |" >> $GITHUB_STEP_SUMMARY
          echo "| High | $HIGH_VULNS |" >> $GITHUB_STEP_SUMMARY

  code-scanning:
    name: "Static Code Analysis"
    container:
      image: "cimg/openjdk:23.0-node"
    steps:
      - name: "Checkout"
        uses: actions/checkout@v4
      
      - name: "Setup Java"
        uses: actions/setup-java@v4
        with:
          distribution: 'temurin'
          java-version: '23'
      
      - name: "Cache Gradle dependencies"
        uses: https://github.com/actions/cache@v4
        with:
          path: |
            ~/.gradle/caches
            ~/.gradle/wrapper
            backend/.gradle
          key: gradle-${{ runner.os }}-${{ hashFiles('backend/build.gradle.kts', 'backend/gradle/wrapper/gradle-wrapper.properties') }}
          restore-keys: |
            gradle-${{ runner.os }}-
      
      - name: "Setup Gradle"
        working-directory: ./backend
        run: chmod +x ./gradlew
      
      - name: "Install SpotBugs"
        working-directory: ./backend
        run: |
          cat <<EOT >> build.gradle.kts
          
          plugins {
            id("com.github.spotbugs") version "6.0.11"
          }
          
          spotbugs {
            ignoreFailures.set(true)
            showProgress.set(true)
            reportsDir.set(file("\$buildDir/reports/spotbugs"))
            effort.set(com.github.spotbugs.snom.Effort.MAX)
          }
          
          tasks.spotbugsMain {
            reports {
              create("html") {
                required.set(true)
                outputLocation.set(file("\$buildDir/reports/spotbugs/main.html"))
              }
            }
          }
          EOT
      
      - name: "Run SpotBugs"
        working-directory: ./backend
        run: ./gradlew spotbugsMain
      
      - name: "Upload SpotBugs Report"
        uses: actions/upload-artifact@v4
        with:
          name: spotbugs-report
          path: backend/build/reports/spotbugs/
          retention-days: 30
      
      - name: "Install ESLint"
        working-directory: ./frontend
        run: npm install --no-save eslint eslint-plugin-security
      
      - name: "Run ESLint Security Plugin"
        working-directory: ./frontend
        run: |
          cat <<EOT > .eslintrc.security.js
          module.exports = {
            "plugins": ["security"],
            "extends": ["plugin:security/recommended"]
          }
          EOT
          
          npx eslint -c .eslintrc.security.js 'src/**/*.ts' -f json > eslint-security-report.json || true
      
      - name: "Upload ESLint Security Report"
        uses: actions/upload-artifact@v4
        with:
          name: eslint-security-report
          path: frontend/eslint-security-report.json
          retention-days: 30
      
      - name: "Summarize Security Findings"
        run: |
          echo "### Static Code Analysis Summary" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "Security reports have been uploaded as artifacts." >> $GITHUB_STEP_SUMMARY
          
          SPOTBUGS_ISSUES=$(grep -c "BugInstance" backend/build/reports/spotbugs/main.xml || echo "0")
          echo "- SpotBugs identified $SPOTBUGS_ISSUES potential issues" >> $GITHUB_STEP_SUMMARY
          
          ESLINT_ISSUES=$(grep -c "severity" frontend/eslint-security-report.json || echo "0")
          echo "- ESLint Security Plugin identified $ESLINT_ISSUES potential issues" >> $GITHUB_STEP_SUMMARY

  secret-scanning:
    name: "Secret Scanning"
    runs-on: ubuntu-latest
    steps:
      - name: "Checkout"
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
      
      - name: "Install Gitleaks"
        run: |
          curl -L https://github.com/zricethezav/gitleaks/releases/download/v8.18.1/gitleaks_8.18.1_linux_x64.tar.gz | tar xz
          chmod +x gitleaks
          sudo mv gitleaks /usr/local/bin/
      
      - name: "Run Gitleaks"
        run: |
          gitleaks detect --source . --report-path gitleaks-report.json --redact --no-git || true
      
      - name: "Upload Gitleaks Report"
        uses: actions/upload-artifact@v4
        with:
          name: gitleaks-report
          path: gitleaks-report.json
          retention-days: 30
      
      - name: "Summarize Secret Findings"
        run: |
          echo "### Secret Scanning Summary" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          
          # Check if any secrets were found
          if [ -s gitleaks-report.json ]; then
            SECRETS_COUNT=$(jq length gitleaks-report.json)
            echo "⚠️ **$SECRETS_COUNT potential secrets found in the codebase**" >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
            echo "Please review the detailed report in the artifacts." >> $GITHUB_STEP_SUMMARY
          else
            echo "✅ No leaked secrets detected in the codebase" >> $GITHUB_STEP_SUMMARY
          fi

  security-report:
    name: "Security Report"
    needs: [dependency-check, code-scanning, secret-scanning]
    if: always()
    steps:
      - name: "Summarize Security Scan"
        run: |
          echo "# 🔒 Security Scan Complete" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "## Summary" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          
          # Check each job status and create summary
          DEP_CHECK="${{ needs.dependency-check.result }}"
          CODE_SCAN="${{ needs.code-scanning.result }}"
          SECRET_SCAN="${{ needs.secret-scanning.result }}"
          
          echo "| Check | Status |" >> $GITHUB_STEP_SUMMARY
          echo "| --- | --- |" >> $GITHUB_STEP_SUMMARY
          
          if [ "$DEP_CHECK" == "success" ]; then
            echo "| Dependency Check | ✅ Complete |" >> $GITHUB_STEP_SUMMARY
          else
            echo "| Dependency Check | ⚠️ Potential issues found |" >> $GITHUB_STEP_SUMMARY
          fi
          
          if [ "$CODE_SCAN" == "success" ]; then
            echo "| Static Code Analysis | ✅ Complete |" >> $GITHUB_STEP_SUMMARY
          else
            echo "| Static Code Analysis | ⚠️ Potential issues found |" >> $GITHUB_STEP_SUMMARY
          fi
          
          if [ "$SECRET_SCAN" == "success" ]; then
            echo "| Secret Scanning | ✅ Complete |" >> $GITHUB_STEP_SUMMARY
          else
            echo "| Secret Scanning | ⚠️ Potential issues found |" >> $GITHUB_STEP_SUMMARY
          fi
          
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "All reports have been uploaded as artifacts. Please review them for detailed information." >> $GITHUB_STEP_SUMMARY