name: docs
on:
  workflow_dispatch:
  workflow_run:
    workflows: ["Publish"]
    branches: [main]
    types: 
      - completed

jobs:
  publish:
    runs-on: ubuntu-latest
    env:
      cache-key: nostr-geotags-docs
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v3

      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '20' # Use a Node.js version that supports ES Modules
          registry-url: 'https://registry.npmjs.org'

      - name: Install Dependencies
        run: yarn install

      - name: Run Tests
        run: yarn test

      - name: Build Package
        run: yarn build

      - name: Create the docs directory locally in CI
        run: npx typedoc src/index.ts

      - name: Hash docs
        id: hash
        run: |
          echo "docs=${{hashFiles('docs')}}" >> "$GITHUB_OUTPUT"

      - name: Cache Docs
        id: docs-cache
        uses: actions/cache/save@v3
        with:
          path: docs
          key: ${{ env.cache-key }}-${{ steps.hash.outputs.docs }}
      
      - name: Change branch
        run: git fetch --all && git checkout gh-pages

      - name: Reset Branch
        run: rm -rf *

      - name: Restore Docs
        uses: actions/cache/restore@v3
        id: cache-restore
        with: 
          path: docs
          key: ${{ env.cache-key }}-${{ steps.hash.outputs.docs }}
          fail-on-cache-miss: true
      
      - name: Configure Git
        run: |
          git config --local user.email "299465+dskvr@users.noreply.github.com"
          git config --local user.name "sandwich [bot]"

      - name: Set Remote URL with PAT
        run: git remote set-url origin https://${{ github.token }}@github.com/${{ github.repository }}

      - name: Commit and Push Documentation
        run: |
          mv docs/* ./
          rm -rf docs 
          git add .
          git commit -m "Update Docs" -a || echo "No changes to commit"
          git push origin gh-pages
