name: Forward failed backport alert to Slack

on:
  issue_comment:
    types: [created]

jobs:
  check_comment:
    runs-on: ubuntu-latest
    if: >
      github.event.issue.pull_request != null &&
      contains(fromJSON('["MEMBER", "COLLABORATOR", "OWNER"]'), github.event.comment.author_association) &&
      contains(github.event.comment.body, 'cherry-pick the changes locally and resolve any conflicts')

    steps:
    - name: Fetch mapping file
      id: fetch_mapping
      uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
      env:
        ACCESS_TOKEN: ${{ secrets.PAT }}
      with:
        script: |
          const url = 'https://raw.githubusercontent.com/Kong/github-slack-mapping/main/mapping.json';
          const headers = {Authorization: `token ${process.env.ACCESS_TOKEN}`};
          const response = await fetch(url, {headers});
          const mapping = await response.json();
          return mapping;

    - name: Generate Slack Payload
      id: generate-payload
      uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
      env:
        SLACK_CHANNEL: gateway-notifications
        SLACK_MAPPING: "${{ steps.fetch_mapping.outputs.result }}"
        PR_URL: ${{ github.event.issue.pull_request.html_url }}
        PR_AUTHOR: ${{ github.event.issue.user.login }}
      with:
        script: |
          const pr_url = process.env.PR_URL;
          const slack_mapping = JSON.parse(process.env.SLACK_MAPPING);
          const pr_author_github_id = process.env.PR_AUTHOR;
          const pr_author_slack_id = slack_mapping[pr_author_github_id];
          const author = pr_author_slack_id ? `<@${pr_author_slack_id}>` : pr_author_github_id;
          const payload = {
            text: `${pr_url} from ${author} failed to backport.`,
            channel: process.env.SLACK_CHANNEL,
          };
          return JSON.stringify(payload);
        result-encoding: string

    - name: Send Slack Message
      uses: slackapi/slack-github-action@45a88b9581bfab2566dc881e2cd66d334e621e2c # v3.0.3
      with:
        payload: ${{ steps.generate-payload.outputs.result }}
        webhook: ${{ secrets.SLACK_GATEWAY_NOTIFICATIONS_WEBHOOK }}
        webhook-type: incoming-webhook
