import com.sonymusic.Utils

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

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

    withCredentials([string(credentialsId: 'orchardci-webhook-token', variable: 'GITHUB_TOKEN')]) {
        def response = sh(script: """
            set +x
            curl -X POST -H "Authorization: token \${GITHUB_TOKEN}" \
            -H "Accept: application/vnd.github+json" \
            -H "X-GitHub-Api-Version: 2022-11-28" \
            -d '{"body": "${params.message}"}' \
            https://api.github.com/repos/${params.owner}/${params.repo}/issues/${params.pullRequestId}/comments
        """, returnStdout: true)
        return readJSON(text: response)
    }
}
