name: Scheduled Maintenance

on:
  schedule:
    # Run every Monday at 9 AM UTC
    - cron: '0 9 * * 1'
  workflow_dispatch:

jobs:
  # Update dependencies
  update-dependencies:
    name: Update Dependencies
    runs-on: ubuntu-latest
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v4

      - name: 🔧 Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18.x'
          cache: 'npm'

      - name: 📦 Update dependencies
        run: |
          npx npm-check-updates -u --target minor
          npm install

      - name: 🧪 Run tests
        run: npm test
        continue-on-error: true

      - name: 📝 Create Pull Request
        uses: peter-evans/create-pull-request@v5
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          commit-message: 'chore: update dependencies'
          title: '⬆️ Update Dependencies'
          body: |
            ## 📦 Dependency Updates
            
            This PR updates project dependencies to their latest minor versions.
            
            ### Checklist
            - [ ] Tests pass
            - [ ] Build succeeds
            - [ ] No breaking changes
            
            ---
            *Automated PR created by scheduled workflow*
          branch: deps/update-dependencies
          delete-branch: true

  # Clean up old artifacts
  cleanup-artifacts:
    name: Clean Old Artifacts
    runs-on: ubuntu-latest
    
    steps:
      - name: 🧹 Delete old artifacts
        uses: actions/github-script@v6
        with:
          script: |
            const days = 30;
            const ms_per_day = 86400000;
            const cutoff = Date.now() - (days * ms_per_day);
            
            const repos = await github.rest.repos.listForOrg({
              org: context.repo.owner,
              type: 'all'
            });
            
            for (const repo of repos.data) {
              const artifacts = await github.rest.actions.listArtifactsForRepo({
                owner: context.repo.owner,
                repo: repo.name
              });
              
              for (const artifact of artifacts.data.artifacts) {
                if (Date.parse(artifact.created_at) < cutoff) {
                  await github.rest.actions.deleteArtifact({
                    owner: context.repo.owner,
                    repo: repo.name,
                    artifact_id: artifact.id
                  });
                  console.log(`Deleted ${artifact.name} from ${repo.name}`);
                }
              }
            }

  # Security audit
  security-audit:
    name: Weekly Security Audit
    runs-on: ubuntu-latest
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v4

      - name: 🔧 Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18.x'
          cache: 'npm'

      - name: 📦 Install dependencies
        run: npm ci

      - name: 🔒 Run security audit
        run: |
          echo "## Security Audit Report" > audit-report.md
          echo "Date: $(date)" >> audit-report.md
          echo "" >> audit-report.md
          
          echo "### NPM Audit" >> audit-report.md
          npm audit --json > npm-audit.json || true
          
          if [ -s npm-audit.json ]; then
            vulnerabilities=$(jq '.metadata.vulnerabilities' npm-audit.json)
            echo "Found vulnerabilities: $vulnerabilities" >> audit-report.md
            
            # Extract critical and high vulnerabilities
            jq -r '.vulnerabilities | to_entries[] | select(.value.severity == "critical" or .value.severity == "high") | "- \(.key): \(.value.severity)"' npm-audit.json >> audit-report.md || true
          else
            echo "✅ No vulnerabilities found" >> audit-report.md
          fi

      - name: 📊 Create issue if vulnerabilities found
        uses: actions/github-script@v6
        with:
          script: |
            const fs = require('fs');
            const report = fs.readFileSync('audit-report.md', 'utf8');
            
            if (report.includes('critical') || report.includes('high')) {
              await github.rest.issues.create({
                owner: context.repo.owner,
                repo: context.repo.repo,
                title: '🔒 Security Audit - Vulnerabilities Found',
                body: report,
                labels: ['security', 'automated']
              });
            }

  # Stale issue management
  manage-stale:
    name: Manage Stale Issues
    runs-on: ubuntu-latest
    
    steps:
      - name: 🏷️ Mark stale issues
        uses: actions/stale@v8
        with:
          repo-token: ${{ secrets.GITHUB_TOKEN }}
          stale-issue-message: >
            This issue has been automatically marked as stale because it has not had
            recent activity. It will be closed if no further activity occurs. Thank you
            for your contributions.
          stale-pr-message: >
            This PR has been automatically marked as stale because it has not had
            recent activity. It will be closed if no further activity occurs. Please
            update or merge if this is still relevant.
          close-issue-message: 'This issue was closed due to inactivity.'
          close-pr-message: 'This PR was closed due to inactivity.'
          days-before-stale: 30
          days-before-close: 7
          stale-issue-label: 'stale'
          stale-pr-label: 'stale'
          exempt-issue-labels: 'pinned,security'
          exempt-pr-labels: 'pinned,awaiting-review'

  # Performance monitoring
  performance-check:
    name: Performance Baseline
    runs-on: ubuntu-latest
    if: false # Enable for production apps
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v4

      - name: 🔧 Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18.x'
          cache: 'npm'

      - name: 📦 Install dependencies
        run: npm ci

      - name: 🏗️ Build application
        run: npm run build

      - name: 📊 Measure performance
        run: |
          # Add your performance measurement script here
          echo "Measuring bundle size..."
          du -sh .next 2>/dev/null || du -sh dist 2>/dev/null || echo "No build output"
          
          echo "Analyzing build..."
          npx bundle-analyzer || echo "Bundle analyzer not configured"

      - name: 📈 Store metrics
        uses: actions/github-script@v6
        with:
          script: |
            // Store performance metrics as GitHub metrics or in external service
            console.log('Performance metrics stored');

  # Database backup (if applicable)
  database-backup:
    name: Database Backup
    runs-on: ubuntu-latest
    if: false # Enable if you have a database to backup
    
    steps:
      - name: 🔧 Setup PostgreSQL client
        run: |
          sudo apt-get update
          sudo apt-get install -y postgresql-client

      - name: 💾 Backup database
        env:
          DATABASE_URL: ${{ secrets.DATABASE_URL }}
        run: |
          # Parse DATABASE_URL and create backup
          echo "Creating database backup..."
          # pg_dump $DATABASE_URL > backup_$(date +%Y%m%d).sql
          echo "Backup created"

      - name: 📤 Upload to S3
        if: false # Enable if using S3
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        run: |
          # Upload backup to S3
          echo "Uploading backup to S3..."
          # aws s3 cp backup_*.sql s3://your-backup-bucket/