import com.sonymusic.Utils
import static com.sonymusic.MetadataUtils.*
import hudson.model.Result

def call(Map args) {
    def params = Utils.validateParams('checkMainPipelineStatus', args, [
        jobName: [type: String, required: false, defaultValue: env.JOB_NAME],
        mainBranch: [type: String, required: false, defaultValue: 'master'],
    ])

    assert params.jobName: 'checkMainPipelineStatus: jobName is required if env.JOB_NAME is not available.'

    if (params.jobName.contains('/PR-')) {
        def appName = params.jobName.split('/PR-')[0].split('/').last()
        def orgName = params.jobName.split('/PR-')[0].split('/')[0]
        def mainBranchJobName = "${orgName}/${appName}/${params.mainBranch}"
        def mainBranchJobUrl = "${env.JENKINS_URL}job/${orgName}/job/${appName}/job/${params.mainBranch}/"

        echo "Checking status of the main pipeline ${mainBranchJobName}"
        def status = getLastCompletedBuildStatus(mainBranchJobName)

        if (status) {
            if (status == Result.SUCCESS) {
                githubPostCommitStatus(
                    repo: appName,
                    state: "success",
                    description: "The build pipeline for this service is green.",
                    context: "Main Branch Pipeline Status",
                    targetUrl: mainBranchJobUrl,
                )
            } else {
                githubPostCommitStatus(
                    repo: appName,
                    state: "failure",
                    description: "CAUTION: The build pipeline for this service is red. Last build status: ${status}.",
                    context: "Main Branch Pipeline Status",
                    targetUrl: mainBranchJobUrl,
                )
            }
        } else {
            echo "Unable to get status of last successful build for ${mainBranchJobName}, skipping the step."
        }
    } else {
        echo "Not a pull request, skipping the step."
    }
}
