name: Deploy Web (dev)

# Builds apps/web and publishes it to the DEV Cloudflare Pages project (bloom-dashboard) - the web
# half of the dev environment (paired with deploy-dev.yml's API). It runs only after CI (all
# stages: security, test, build) succeeds on main, so a red pipeline never deploys. No-op until the
# Cloudflare account is configured (guarded on CLOUDFLARE_ACCOUNT_ID).
#
# The SPA builds same-origin (empty VITE_API_BASE_URL): the Pages Function (apps/web/functions)
# reverse-proxies /api to the API. Which API it targets is the project's API_ORIGIN Pages env var
# (defaults to the dev API). Production is a separate project/workflow (deploy-web-production.yml).

on:
  workflow_run:
    workflows: ["CI"]
    types: [completed]
    branches: [main]
  workflow_dispatch:

concurrency:
  group: deploy-web-dev
  cancel-in-progress: true

jobs:
  deploy:
    # Auto runs only when CI succeeded (all stages passed on main); manual runs always proceed.
    if: >-
      ${{ vars.CLOUDFLARE_ACCOUNT_ID != '' &&
          (github.event_name == 'workflow_dispatch' ||
           github.event.workflow_run.conclusion == 'success') }}
    runs-on: bloom-arc
    steps:
      - uses: actions/checkout@v4
        with:
          ref: main

      - uses: pnpm/action-setup@v4
        with:
          version: 10.6.3

      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: pnpm
          cache-dependency-path: pnpm-lock.yaml

      # Workspace-root install (single lockfile, #481); build + publish stay in apps/web.
      - name: Install dependencies
        run: pnpm install --frozen-lockfile

      - name: Build
        working-directory: apps/web
        env:
          VITE_API_BASE_URL: ${{ vars.VITE_API_BASE_URL }}
        run: pnpm run build

      - name: Publish to Cloudflare Pages (dev)
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
          workingDirectory: apps/web
          packageManager: pnpm
          command: >-
            pages deploy dist
            --project-name=${{ vars.CLOUDFLARE_PAGES_PROJECT || 'bloom-dashboard' }}
            --branch=main
