name: Update Swagger

on:
  workflow_dispatch:
  push:
    branches:
      - master

# cancel in-progress jobs if a new job is triggered
# This is useful to avoid running multiple builds for the same branch if a new commit is pushed
# or a pull request is updated.
# It helps to save resources and time by ensuring that only the latest commit is built and tested
# This is particularly useful for long-running jobs that may take a while to complete.
# The `group` is set to a combination of the workflow name, event name, and branch name.
# This ensures that jobs are grouped by the workflow and branch, allowing for cancellation of
# in-progress jobs when a new commit is pushed to the same branch or a new pull request is opened.
concurrency:
  group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.ref_name || github.ref }}
  cancel-in-progress: true

permissions:
  contents: read

jobs:
  push:
    runs-on: ubuntu-latest
    steps:
      - name: Harden Runner
        uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
        with:
          egress-policy: audit

      - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0

      - name: Set up JDK 17
        uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
        with:
          java-version: "17"
          distribution: "temurin"

      - uses: gradle/actions/setup-gradle@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0

      - name: Generate Swagger documentation
        run: ./gradlew :stirling-pdf:generateOpenApiDocs

      - name: Upload Swagger Documentation to SwaggerHub
        run: ./gradlew swaggerhubUpload
        env:
          SWAGGERHUB_API_KEY: ${{ secrets.SWAGGERHUB_API_KEY }}
          SWAGGERHUB_USER: "Frooodle"

      - name: Get version number
        id: versionNumber
        run: echo "versionNumber=$(./gradlew printVersion --quiet | tail -1)" >> $GITHUB_OUTPUT

      - name: Set API version as published and default on SwaggerHub
        run: |
          curl -X PUT -H "Authorization: ${SWAGGERHUB_API_KEY}" "https://api.swaggerhub.com/apis/${SWAGGERHUB_USER}/Stirling-PDF/${{ steps.versionNumber.outputs.versionNumber }}/settings/lifecycle" -H  "accept: application/json" -H  "Content-Type: application/json" -d "{\"published\":true,\"default\":true}"
        env:
          SWAGGERHUB_API_KEY: ${{ secrets.SWAGGERHUB_API_KEY }}
          SWAGGERHUB_USER: "Frooodle"
