# Add labels in pull request
name: approve_label

on:
  pull_request:
  pull_request_review:
    types: [submitted]


permissions: {}

jobs:
  trigger-tests:
    name: approve_label/trigger-tests
    runs-on: ubuntu-latest
    permissions:
      pull-requests: write
    steps:
      - name: Get current labels
        uses: snnaplab/get-labels-action@f426df40304808ace3b5282d4f036515f7609576

      # Remove label if a push is performed after an approval
      - name: Remove approved label
        if: ${{ github.event_name == 'pull_request' && contains(fromJSON(env.LABELS), 'approved') }}
        uses: actions-ecosystem/action-remove-labels@2ce5d41b4b6aa8503e285553f75ed56e0a40bae0
        with:
          # We use a PAT to have the same user (zama-bot) for label deletion as for creation.
          github_token: ${{ secrets.FHE_ACTIONS_TOKEN }}
          labels: approved

      # Add label only if the review is approved and if the label doesn't already exist
      - name: Add approved label
        uses: actions-ecosystem/action-add-labels@18f1af5e3544586314bbe15c0273249c770b2daf
        if: ${{ github.event_name == 'pull_request_review' 
          && github.event.review.state == 'approved'
          && !contains(fromJSON(env.LABELS), 'approved') }}
        with:
          # We need to use a PAT to be able to trigger `labeled` event for the other workflow.
          github_token: ${{ secrets.FHE_ACTIONS_TOKEN }}
          labels: approved

      - name: Check if maintainer needs to handle label manually
        if: ${{ failure() }}
        run: |
          echo "Pull-request from an external contributor."
          echo "A maintainer need to manually add/remove the 'approved' label."
          exit 1
