name: DeployCloudflarePages

on:
  # Enable workflow_run in only one of deploy-github-pages.yml or deploy-cloudflare-pages.yml.
  # workflow_run:
  #   workflows: ['CollectSkills']
  #   types: [completed]
  #   branches: [main]
  workflow_dispatch:

permissions:
  contents: read

concurrency:
  group: 'cloudflare-pages'
  cancel-in-progress: false

jobs:
  deploy:
    runs-on: ubuntu-latest
    env:
      CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
      CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
      CLOUDFLARE_PAGES_PROJECT_NAME: ${{ vars.CLOUDFLARE_PAGES_PROJECT_NAME }}
    if: ${{ (github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success') && (github.event_name != 'workflow_dispatch' || github.ref_name == 'main') }}
    steps:
      - name: Check Cloudflare Pages configuration
        id: preflight
        run: |
          if [ -n "$CLOUDFLARE_API_TOKEN" ] && [ -n "$CLOUDFLARE_ACCOUNT_ID" ] && [ -n "$CLOUDFLARE_PAGES_PROJECT_NAME" ]; then
            echo "enabled=true" >> "$GITHUB_OUTPUT"
          else
            echo "enabled=false" >> "$GITHUB_OUTPUT"
            echo "Cloudflare Pages is not configured. Skipping deploy."
          fi

      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        if: ${{ steps.preflight.outputs.enabled == 'true' }}

      - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v4.4.0
        if: ${{ steps.preflight.outputs.enabled == 'true' }}
        with:
          version: 10

      - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
        if: ${{ steps.preflight.outputs.enabled == 'true' }}
        with:
          node-version: '24'

      - name: Install web dependencies
        if: ${{ steps.preflight.outputs.enabled == 'true' }}
        run: pnpm install

      - name: Build
        if: ${{ steps.preflight.outputs.enabled == 'true' }}
        run: pnpm build

      - name: Deploy to Cloudflare Pages
        if: ${{ steps.preflight.outputs.enabled == 'true' }}
        run: pnpm dlx wrangler pages deploy build --project-name "$CLOUDFLARE_PAGES_PROJECT_NAME"
