name: Documentation

on:
  pull_request:
  push:
    branches:
      - main
    tags:
      - "v*"
  workflow_dispatch:

concurrency:
  group: "pages-${{ github.ref }}"
  cancel-in-progress: true

jobs:
  docs:
    name: Build and Deploy Documentation
    runs-on: ubuntu-latest
    if: secrets.CLOUDFLARE_API_TOKEN != ''

    steps:
      - name: Sync repository
        uses: actions/checkout@v6
        with:
          persist-credentials: false
          fetch-depth: 0

      - name: Detect runner environment
        id: runner-env
        uses: https://git.tomfos.tr/actions/detect-versions@v1

      - name: Setup Node.js
        if: steps.runner-env.outputs.node_major == '' || steps.runner-env.outputs.node_major < '20'
        uses: https://github.com/actions/setup-node@v6
        with:
          node-version: 22

      - name: Cache npm dependencies
        uses: actions/cache@v3
        with:
          path: ~/.npm
          key: continuwuity-rspress-${{ steps.runner-env.outputs.slug }}-${{ steps.runner-env.outputs.arch }}-node-${{ steps.runner-env.outputs.node_version }}-${{ hashFiles('package-lock.json') }}
          restore-keys: |
            continuwuity-rspress-${{ steps.runner-env.outputs.slug }}-${{ steps.runner-env.outputs.arch }}-node-${{ steps.runner-env.outputs.node_version }}-
            continuwuity-rspress-${{ steps.runner-env.outputs.slug }}-${{ steps.runner-env.outputs.arch }}-node-

      - name: Install dependencies
        run: npm ci

      - name: Build Rspress documentation
        run: npm run docs:build

      - name: Install Wrangler
        run: npm install --save-dev wrangler@latest

      - name: Deploy to Cloudflare Pages (Production)
        if: github.ref == 'refs/heads/main' && vars.CLOUDFLARE_PROJECT_NAME != ''
        uses: https://github.com/cloudflare/wrangler-action@v3
        with:
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          command: pages deploy ./doc_build --branch="main" --commit-dirty=true --project-name="${{ vars.CLOUDFLARE_PROJECT_NAME }}"

      - name: Deploy to Cloudflare Pages (Preview)
        if: github.ref != 'refs/heads/main' && vars.CLOUDFLARE_PROJECT_NAME != ''
        uses: https://github.com/cloudflare/wrangler-action@v3
        with:
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          command: pages deploy ./doc_build --branch="${{ github.head_ref || github.ref_name }}" --commit-dirty=true --project-name="${{ vars.CLOUDFLARE_PROJECT_NAME }}"
