name: Security Audit

# This workflow is called by the main CI workflow
# Also runs on schedule for regular security checks
on:
  workflow_call:
  schedule:
    # Run comprehensive security audit weekly on Sundays at 2 AM UTC
    - cron: '0 2 * * 0'

jobs:
  security-audit:
    runs-on: ubuntu-latest
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 1  # Shallow clone sufficient for security checks
          
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: 'npm'
          
      - name: Install dependencies
        run: npm ci
        
      - name: Comprehensive security audit
        run: |
          echo "Running comprehensive security audit..."
          npm run audit:ci
          
          echo "Summary of high vulnerabilities (blocking):"
          npm audit --audit-level=high --json | jq -r '.metadata.vulnerabilities.high // 0' | xargs -I {} echo "High vulnerabilities: {}"
          

  license-check:
    runs-on: ubuntu-latest
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 1  # Shallow clone sufficient for license checks
        
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: 'npm'
          
      - name: Install dependencies
        run: npm ci
        
      - name: Check licenses
        run: |
          echo "Checking package licenses..."
          npm run license-check || {
            echo "❌ Unapproved licenses detected"
            echo "Please review and approve the licenses in the package dependencies"
            exit 1
          }
          echo "✅ All licenses are approved"
