name: Fetch Tailor Platform Token
description: Fetch an access token via PFMU OAuth2 or PAT fallback and expose it as the `token` output.

inputs:
  client_id:
    description: "PFMU OAuth2 client ID (leave empty to use PAT)"
    required: false
    default: ""
  client_secret:
    description: "PFMU OAuth2 client secret"
    required: false
    default: ""
  token:
    description: "Personal access token (used when client_id is empty)"
    required: false
    default: ""
  platform_oauth2_url:
    description: "Tailor Platform OAuth2 token URL"
    required: false
    default: "https://api.tailor.tech/oauth2/platform/token"

outputs:
  token:
    description: >-
      Resolved Tailor Platform access token. Pass it to consumers via an
      explicit per-step env var sourced from this step's output (or a
      composite action's own `token` input) rather than a global env var,
      since writing secrets to $GITHUB_ENV is itself a code-execution risk
      for later steps.
    value: ${{ steps.pfmu.outputs.token || steps.pat.outputs.token }}

runs:
  using: composite
  steps:
    - name: Fetch PFMU token
      id: pfmu
      if: inputs.client_id != ''
      shell: bash
      env:
        OAUTH2_URL: ${{ inputs.platform_oauth2_url }}
        CLIENT_ID: ${{ inputs.client_id }}
        CLIENT_SECRET: ${{ inputs.client_secret }}
      run: |
        if ! RESPONSE=$(
          curl -sS -f --max-time 30 -X POST "$OAUTH2_URL" \
            -H "Content-Type: application/x-www-form-urlencoded" \
            --data-urlencode "grant_type=client_credentials" \
            --data-urlencode "client_id=$CLIENT_ID" \
            --data-urlencode "client_secret=$CLIENT_SECRET"
        ); then
          echo "::error::Failed to fetch PFMU access token"
          exit 1
        fi
        ACCESS_TOKEN=$(printf '%s' "$RESPONSE" | jq -r '.access_token')
        if [ -z "$ACCESS_TOKEN" ] || [ "$ACCESS_TOKEN" = "null" ]; then
          echo "::error::Access token missing or null in OAuth2 response"
          exit 1
        fi
        echo "::add-mask::$ACCESS_TOKEN"
        echo "token=$ACCESS_TOKEN" >> "$GITHUB_OUTPUT"

    - name: Use PAT token
      id: pat
      if: inputs.client_id == '' && inputs.token != ''
      shell: bash
      env:
        INPUT_TOKEN: ${{ inputs.token }}
      run: |
        echo "::add-mask::$INPUT_TOKEN"
        echo "token=$INPUT_TOKEN" >> "$GITHUB_OUTPUT"

    - name: Fail if no credentials
      if: inputs.client_id == '' && inputs.token == ''
      shell: bash
      run: |
        echo "::error::No credentials provided. Set either client_id+client_secret (PFMU) or token (PAT)."
        exit 1
