name: Teardown playground preview
on:
  pull_request:
    types: [unlabeled, closed]

jobs:
  teardown:
    # check whether the unlabel name was deploy-preview || check whether the PR was closed / merged and whether deploy-preview was part of the array
    if: github.event.label.name == 'deploy-preview' || (github.event.action == 'closed' && contains( github.event.pull_request.labels.*.name, 'deploy-preview'))
    name: teardown-${{ github.head_ref || github.event.ref }} # env is not yet available here
    runs-on: ubuntu-latest
    env:
      BRANCH_NAME: ${{ github.head_ref || github.event.ref }} # head_ref = branch on PR, event.ref stable/**
    steps:
      - id: sanitize
        name: Sanitize form-playground branch name
        uses: camunda/infra-global-github-actions/sanitize-branch-name@main
        with:
          branch: ${{ env.BRANCH_NAME }}
          max_length: '25'
      - name: Save form-playground branch name
        run: echo "PREVIEW_BRANCH_NAME=demo-${{ steps.sanitize.outputs.branch_name }}" >> $GITHUB_ENV
      - name: Remove form-playground branch
        uses: dawidd6/action-delete-branch@145cd9febe29b6d83e19682d4b95849b851f544c
        with:
          github_token: ${{ secrets.ADD_TO_HTO_PROJECT_PAT }}
          owner: camunda
          repository: form-playground
          branches: ${{ env.PREVIEW_BRANCH_NAME }}
      - uses: bobheadxi/deployments@648679e8e4915b27893bd7dbc35cb504dc915bc8
        if: always()
        name: Deactivate GitHub Deployment environment
        with:
          step: deactivate-env
          env: ${{ env.PREVIEW_BRANCH_NAME }}
          token: ${{ secrets.GITHUB_TOKEN }}
          ref: ${{ env.BRANCH_NAME }}
