name: CI

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

jobs:
  test-and-build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.DEPLOY_TOKEN }}

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - name: Install dependencies
        run: npm ci

      - name: Run tests
        run: npm test

      - name: Build
        run: npm run build

      - name: Push dist to release branch
        if: github.event_name == 'push' && github.ref == 'refs/heads/main'
        run: |
          git config user.name "ci"
          git config user.email "git@limelight.de"

          # Save distributable files before switching branch
          mkdir -p /tmp/release
          cp package.json theme.css font.css /tmp/release/
          cp -r fonts assets /tmp/release/

          # Create a clean orphan branch (no source files)
          git checkout --orphan release
          git rm -rf .

          # Restore distributable files (dist/ survived as it was gitignored)
          cp /tmp/release/package.json .
          npm pkg delete scripts.prepare
          cp /tmp/release/theme.css .
          cp /tmp/release/font.css .
          cp -r /tmp/release/fonts .
          cp -r /tmp/release/assets .

          git add package.json theme.css font.css dist/ fonts/ assets/
          git commit -m "release: $(git log origin/main -1 --pretty=%s)" || echo "nothing to commit"
          git push origin release --force
