# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

name: CLA

on:
  check_run:
    types: [completed]

permissions:
  pull-requests: write

jobs:
  cla-label:
    name: CLA Label
    if: github.event.check_run.name == 'cla/google'
    runs-on: ubuntu-latest
    steps:
      - name: Update CLA label
        uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
        with:
          github-token: ${{ secrets.GOOGLEWORKSPACE_BOT_TOKEN }}
          script: |
            const cr = context.payload.check_run;
            const passed = cr.conclusion === 'success';

            for (const pr of cr.pull_requests) {
              const labels = passed
                ? { add: 'cla: yes', remove: 'cla: no' }
                : { add: 'cla: no', remove: 'cla: yes' };

              await github.rest.issues.addLabels({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: pr.number,
                labels: [labels.add],
              });

              try {
                await github.rest.issues.removeLabel({
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  issue_number: pr.number,
                  name: labels.remove,
                });
              } catch (e) {
                // Label not present — ignore
              }
            }
