import com.sonymusic.Utils

def call(Map args){
    def params = Utils.validateParams('githubPostCommitStatus', args, [
        repo: [type: String, required: true],
        state: [type: String, required: true],
        description: [type: String, required: true],
        context: [type: String, required: true],
        targetUrl: [type: String, required: false, defaultValue: env.JOB_URL],
        owner: [type: String, required: false, defaultValue: 'theorchard'],
        commitHash: [type: String, required: false, defaultValue: env.GIT_COMMIT]
    ])

    assert params.commitHash: 'githubPostCommitStatus: commitHash is required if env.GIT_COMMIT is not available.'
    assert params.targetUrl: 'githubPostCommitStatus: targetUrl is required if env.JOB_URL 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 '{"state":"${params.state}","target_url":"${params.targetUrl}","description":"${params.description}","context":"${params.context}"}' \
            https://api.github.com/repos/${params.owner}/${params.repo}/statuses/${params.commitHash}
        """, returnStdout: true)

        return readJSON(text: response)
    }
}
