# CI студии Рублокса.
# Запускается на каждый push и pull_request.
#
# Что проверяем:
#   1. lint — ESLint без warning'ов
#   2. format-check — Prettier формат не нарушен
#   3. build — vite build проходит без ошибок
#   4. secret-scan — trufflehog не нашёл утечек секретов
#   5. size-check — PR не больше 1000 строк (предупреждение)
name: CI

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  lint:
    name: Lint + Format
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '18'
      - run: npm ci
      - run: npm run format:check
      - run: npm run lint

  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '18'
      - run: npm ci
      - run: npm run build
      - name: Save build size
        run: |
          du -sh build/
          ls -la build/assets/ | head -10

  secret-scan:
    name: Secret scan
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - name: Run trufflehog
        run: |
          docker run --rm -v "$(pwd):/repo" \
            trufflesecurity/trufflehog:latest \
            git file:///repo \
            --only-verified --fail \
            --exclude-paths /repo/.trufflehog-ignore 2>&1 | tee scan.log
          if grep -q "Reason:" scan.log; then
            echo "::error::Найдены секреты в коммитах! См. лог выше."
            exit 1
          fi

  size-check:
    name: PR size check
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - name: Check PR size
        run: |
          ADDED=$(git diff origin/${{ github.base_ref }}...HEAD --shortstat | grep -oE '[0-9]+ insertion' | grep -oE '[0-9]+' || echo 0)
          REMOVED=$(git diff origin/${{ github.base_ref }}...HEAD --shortstat | grep -oE '[0-9]+ deletion' | grep -oE '[0-9]+' || echo 0)
          TOTAL=$((ADDED + REMOVED))
          echo "PR изменяет $TOTAL строк (+$ADDED / -$REMOVED)"
          if [ "$TOTAL" -gt 1000 ]; then
            echo "::warning::PR изменяет $TOTAL строк (> 1000). Подумай о дроблении на несколько меньших."
          fi
