name: Vendoo Production Deploy

on:
  workflow_dispatch:
    inputs:
      target_version:
        description: Expected Vendoo version
        required: true
        type: string
      public_base_url:
        description: Public Vendoo URL
        required: true
        default: https://vendoo.flatlined.de
        type: string

permissions:
  contents: read

concurrency:
  group: vendoo-production-deploy
  cancel-in-progress: false

jobs:
  deploy:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
      - name: Validate inputs
        shell: bash
        env:
          TARGET_VERSION: ${{ inputs.target_version }}
          PUBLIC_BASE_URL: ${{ inputs.public_base_url }}
        run: |
          set -euo pipefail
          [[ "$TARGET_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]
          [[ "$PUBLIC_BASE_URL" =~ ^https://[^/]+/?$ ]]

      - name: Trigger Coolify
        shell: bash
        env:
          COOLIFY_DEPLOY_WEBHOOK_URL: ${{ secrets.COOLIFY_DEPLOY_WEBHOOK_URL }}
        run: |
          set -euo pipefail
          test -n "$COOLIFY_DEPLOY_WEBHOOK_URL"
          curl --fail --silent --show-error --location --request GET \
            --connect-timeout 20 --max-time 90 \
            "$COOLIFY_DEPLOY_WEBHOOK_URL" >/tmp/coolify-response.txt
          echo "Coolify accepted the deployment trigger."

      - name: Wait for exact production version
        shell: bash
        env:
          TARGET_VERSION: ${{ inputs.target_version }}
          PUBLIC_BASE_URL: ${{ inputs.public_base_url }}
        run: |
          set -euo pipefail
          BASE_URL="${PUBLIC_BASE_URL%/}"
          deadline=$((SECONDS + 1500))
          last_version="unknown"
          while (( SECONDS < deadline )); do
            if body=$(curl --fail --silent --show-error --connect-timeout 10 --max-time 30 \
              -H 'Accept: application/json' -H 'Cache-Control: no-cache' \
              "$BASE_URL/readyz?github_run=${GITHUB_RUN_ID}&attempt=${GITHUB_RUN_ATTEMPT}"); then
              ready=$(jq -r '.ok // false' <<<"$body")
              version=$(jq -r '.version // empty' <<<"$body")
              if [[ -n "$version" ]]; then last_version="$version"; fi
              echo "ready=$ready version=${version:-unknown} expected=$TARGET_VERSION"
              if [[ "$ready" == "true" && "$version" == "$TARGET_VERSION" ]]; then exit 0; fi
            fi
            sleep 15
          done
          echo "Timeout waiting for Vendoo $TARGET_VERSION. Last version: $last_version" >&2
          exit 1

      - name: Final health response
        shell: bash
        env:
          PUBLIC_BASE_URL: ${{ inputs.public_base_url }}
        run: |
          set -euo pipefail
          BASE_URL="${PUBLIC_BASE_URL%/}"
          curl --fail --silent --show-error -H 'Accept: application/json' \
            "$BASE_URL/healthz?github_run=${GITHUB_RUN_ID}" | jq .
