name: Deploy Documentation

on:
  push:
    branches: [ main ]
  workflow_dispatch:

permissions:
  contents: read
  pages: write
  id-token: write

concurrency:
  group: "pages"
  cancel-in-progress: false

jobs:
  build:
    name: Build Documentation
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Install mdBook
        uses: peaceiris/actions-mdbook@v2
        with:
          mdbook-version: '0.4.43'

      - name: Setup Pages
        id: pages
        uses: actions/configure-pages@v5

      - name: Build mdBook
        run: cd book && mdbook build

      - name: Build API documentation
        run: cargo doc --all-features --no-deps

      - name: Combine documentation
        run: |
          mkdir -p _site
          # Copy mdBook (user guide) to root
          cp -r book/book/* _site/
          # Copy API docs to /api subdirectory
          mkdir -p _site/api
          cp -r target/doc/* _site/api/
          # Create redirect from /api to /api/alimentar for convenience
          echo '<meta http-equiv="refresh" content="0; url=alimentar/">' > _site/api/index.html
          # Add .nojekyll to prevent GitHub Pages from processing with Jekyll
          touch _site/.nojekyll

      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
          path: _site

  deploy:
    name: Deploy to GitHub Pages
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4
