name: Deploy Documentation

on:
  # Trigger on push to main branch
  push:
    branches:
      - main
      - master  # Also support master branch
    # Only run when docs files change
    paths:
      - 'docs/**'
      - 'apps/edit-docs/**'
      - 'apps/build-docs/**'
      - 'packages/share-theme/**'

  # Allow manual triggering from Actions tab
  workflow_dispatch:

  # Run on pull requests for preview deployments
  pull_request:
    branches:
      - main
      - master
    paths:
      - 'docs/**'
      - 'apps/edit-docs/**'
      - 'apps/build-docs/**'
      - 'packages/share-theme/**'

jobs:
  build-and-deploy:
    name: Build and Deploy Documentation
    runs-on: ubuntu-latest
    timeout-minutes: 10

    # Required permissions for deployment
    permissions:
      contents: read
      deployments: write
      pull-requests: write # For PR preview comments
      id-token: write # For OIDC authentication (if needed)

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v6

      - name: Setup pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: '24'
          cache: 'pnpm'

      - name: Install Dependencies
        run: pnpm install --frozen-lockfile

      - name: Trigger build of documentation
        run: pnpm docs:build

      - name: Validate Built Site
        run: |
          test -f site/index.html || (echo "ERROR: site/index.html not found" && exit 1)
          test -f site/developer-guide/index.html || (echo "ERROR: site/developer-guide/index.html not found" && exit 1)
          echo "✓ User Guide and Developer Guide built successfully"

      - name: Deploy
        uses: ./.github/actions/deploy-to-cloudflare-pages
        if: ${{ github.repository == vars.REPO_MAIN }}
        with:
          project_name: "trilium-docs"
          comment_body: "📚 Documentation preview is ready"
          production_url: "https://docs.triliumnotes.org"
          deploy_dir: "site"
          cloudflare_api_token: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          cloudflare_account_id: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          github_token: ${{ secrets.GITHUB_TOKEN }}
