name: Get or create workspace
description: Resolve the per-PR Tailor Platform workspace (<prefix>-pr<N>), creating it if missing.

# Requires: pnpm install already run.

inputs:
  token:
    description: "Tailor Platform access token (e.g. the `token` output of erp-kit-fetch-tailor-token)."
    required: true
  app:
    description: "App name under apps/ — used to run the tailor CLI in that package context."
    required: true
  workspace_name_prefix:
    description: "Workspace name prefix; the full name is <prefix>-pr<N>. Include the app and a 'test' marker for a unique per-app name (e.g. <repo>-<app>-test)."
    required: true
  organization_id:
    description: "Tailor organization ID (required when the workspace must be created)."
    required: false
    default: ""
  folder_id:
    description: "Tailor folder ID (required when the workspace must be created)."
    required: false
    default: ""
  region:
    description: "Region the workspace is created in (`us-west` or `asia-northeast`). Ignored when the workspace already exists."
    required: false
    default: asia-northeast

outputs:
  workspace_id:
    description: "Workspace ID resolved (found or created) for this run."
    value: ${{ steps.resolve.outputs.workspace_id }}

runs:
  using: composite
  steps:
    - name: Resolve workspace
      id: resolve
      shell: bash
      env:
        TAILOR_PLATFORM_TOKEN: ${{ inputs.token }}
        ORGANIZATION_ID: ${{ inputs.organization_id }}
        FOLDER_ID: ${{ inputs.folder_id }}
        REGION: ${{ inputs.region }}
        WORKSPACE_NAME: ${{ inputs.workspace_name_prefix }}-pr${{ github.event.pull_request.number }}
        APP: ${{ inputs.app }}
        # Reopen recreates the workspace, since close deletes it.
        FORCE_RECREATE: ${{ github.event.action == 'reopened' }}
      run: |
        set -euo pipefail
        echo "Resolving workspace \"$WORKSPACE_NAME\""

        workspace_id=""
        if [ "$FORCE_RECREATE" != "true" ]; then
          workspace_id="$(pnpm -C "apps/$APP/backend" exec tailor workspace list --json \
            | jq -r --arg n "$WORKSPACE_NAME" 'map(select(.name == $n)) | first | .id // ""')"
        fi

        if [ -n "$workspace_id" ]; then
          echo "Found existing workspace_id=$workspace_id"
        else
          echo "Creating workspace \"$WORKSPACE_NAME\""
          workspace_id="$(pnpm -C "apps/$APP/backend" exec tailor workspace create \
            --name "$WORKSPACE_NAME" \
            --region "$REGION" \
            --organization-id "$ORGANIZATION_ID" \
            --folder-id "$FOLDER_ID" \
            --json | jq -r '.id')"
          echo "Created workspace_id=$workspace_id"
        fi

        if [ -z "$workspace_id" ] || [ "$workspace_id" = "null" ]; then
          echo "::error::Failed to resolve or create workspace \"$WORKSPACE_NAME\""
          exit 1
        fi
        echo "workspace_id=$workspace_id" >> "$GITHUB_OUTPUT"
