name: Update Example Site
permissions:
  contents: read
  id-token: write
  pages: write
  pull-requests: write
  checks: write
  statuses: write
  actions: write
on:
  workflow_dispatch:
  schedule:
    - cron: '0 0 * * 0'  # Every Sunday at midnight

jobs:
  update-example-site:
    runs-on: ubuntu-latest
    env:
      DATE: ${{ format('YYYY-MM-DD', github.event.repository.pushed_at) }}
      
    steps:
      - name: Set date
        run: echo "DATE=$(date +'%Y-%m-%d')" >> $GITHUB_ENV
      
      - name: Set branch name
        run: echo "BRANCH_NAME=update/exampleSite-${DATE}" >> $GITHUB_ENV

      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Install Node.js dependencies
        run: npm i

      - name: Update example site content
        run: |
          cd exampleSite
          ../node_modules/@zetxek/adritian-theme-helper/dist/scripts/download-content.js

      - name: Create new branch
        run: |
          git checkout -b ${{ env.BRANCH_NAME }}

      - name: Commit changes
        run: |
          git config --global user.name 'GitHub Actions'
          git config --global user.email 'actions@github.com'
          git add .
          git commit -m "Update example site content"

      - name: Push changes
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          git push origin ${{ env.BRANCH_NAME }}

      - name: Create Pull Request
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          PR_TITLE="ExampleSite content update (${DATE})"
          PR_BODY="This automated PR updates the example site with the latest content from [adritian-demo](https://github.com/zetxek/adritian-demo).
          
          **Overview of changes:**

          <code>
          $(git diff --stat HEAD~1)
          </code>"
          gh pr create --title "$PR_TITLE" --body "$PR_BODY" --base main --head "${{ env.BRANCH_NAME }}"
