name: Lint and Format

on:
  push:
    branches: ["**"]
  pull_request:
    branches: ["**"]

jobs:
  lint:
    name: ESLint
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node
        uses: oven-sh/setup-bun@v2
        with:
          bun-version: latest

      - name: Install dependencies
        run: bun install

      - name: Run ESLint
        run: bun run lint

      - name: Run Prettier check
        run: bun run format:check

  format:
    name: Auto-format (eslint --fix)
    runs-on: ubuntu-latest
    needs: lint
    if: github.event_name == 'push'
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          persist-credentials: true

      - name: Setup Node
        uses: oven-sh/setup-bun@v2
        with:
          bun-version: latest

      - name: Install dependencies
        run: bun install

      - name: Run Prettier --write
        run: bun run format

      - name: Run ESLint --fix
        run: bun run lint:fix

      - name: Commit & push fixes
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          if ! git diff --quiet; then
            git add -A
            git commit -m "chore: auto format by GitHub Actions" || echo "No changes to commit"
            git push
          else
            echo "No formatting changes"
          fi
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
