import com.sonymusic.Utils

def call(Map args) {
    def params = Utils.validateParams('slackPrNotify', args, [
        channel: [type: String, required: true],
        repo: [type: String, required: true],
        message: [type: String, required: false],
        owner: [type: String, required: false, defaultValue: 'theorchard'],
        pullRequestId: [type: String, required: false, defaultValue: env.CHANGE_ID]
    ])

    assert params.pullRequestId: 'slackPrNotify: pullRequestId is required if env.CHANGE_ID is not available.'

    def pullRequest = getPullRequestDetails(params)
    def message = params.message ?: pullRequest.description

    slackNotify(
        channel: params.channel,
        message: "${pullRequest.title} (${pullRequest.user.login})\n${pullRequest.html_url}\n${message}"
    )
}

def getPullRequestDetails(Map params) {
    withCredentials([string(credentialsId: 'orchardci-webhook-token', variable: 'GITHUB_TOKEN')]) {
        def response = sh(script: """
            set +x
            curl -X GET -H "Authorization: token \${GITHUB_TOKEN}" \
            -H "Accept: application/vnd.github.v3+json" \
            https://api.github.com/repos/${params.owner}/${params.repo}/pulls/${params.pullRequestId}
        """, returnStdout: true)

        return readJSON(text: response)
    }
}
