stages:
  - notify

notify_discord_on_mr_request_main_dev:
  stage: notify
  image: alpine:3.20
  rules:
    # hanya MR yang target ke main atau development
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && ($CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "main" || $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "development")'
      when: on_success
    - when: never

  script:
    - apk add --no-cache curl jq coreutils
    - |
      TIME_HUMAN="$(date '+%d/%m/%y, %H.%M')"
      TIME_ISO="$(date -u +%Y-%m-%dT%H:%M:%SZ)"

      TITLE="${CI_MERGE_REQUEST_TITLE}"
      IID="!${CI_MERGE_REQUEST_IID}"
      USER_LINE="${GITLAB_USER_NAME} (${GITLAB_USER_LOGIN})"
      PROJECT_PATH="${CI_PROJECT_PATH}"
      USERNAME="${GITLAB_USER_LOGIN}"
      MR_URL="${CI_PROJECT_URL}/-/merge_requests/${CI_MERGE_REQUEST_IID}"

      DESC="$(printf "**%s**\n\n%s opened merge request %s %s\n%s" \
        "$USERNAME" "$USER_LINE" "$IID" "$TITLE" "$TIME_HUMAN")"

      payload=$(jq -n \
        --arg desc "$DESC" \
        --arg project "$PROJECT_PATH" \
        --arg timeiso "$TIME_ISO" \
        --arg mrurl "$MR_URL" \
        '{
          "username": "Mock-api - Merge Requests",
          "embeds": [
            {
              "description": ($desc + "\n" + $mrurl),
              "color": 15105570,
              "footer": { "text": $project },
              "timestamp": $timeiso
            }
          ]
        }')

      curl -sS -H "Content-Type: application/json" \
        -d "$payload" \
        "$DISCORD_WEBHOOK_URL"
