def notify(
    String context,
    String giteaUser, 
    String giteaPass, 
    String repositoryUrl, 
    String repositoryName, 
    String commitHash, 
    String buildStatus 
) {
    def status = buildStatus == 'success' ? 'success' : 'failure'
    def description = buildStatus == 'success' ? 'Build succeeded' : 'Build failed'
    
    sh """
    curl -X POST \
        -u "${giteaUser}:${giteaPass}" \
        -H "Content-Type: application/json" \
        -d '{"context":"${context}","state": "${status}", "description": "${description}"}' \
        ${repositoryUrl}${repositoryName}/statuses/${commitHash}
    """
}

pipeline {
    agent any
    environment {
        REGISTRY_NAME = 'registry.entcor/trust-module'
        IMAGE_NAME = "trust-module-frontend"
        GITEA_REPOSITORY_URL = "http://git.entcor/api/v1/repos/" 
    }
    stages {
        stage ('Initialize variables') {
            steps {
                script {
                    echo sh(script: 'env|sort', returnStdout: true)
                    env.IMAGE_TAG = sh(script: "git describe --tags --abbrev=0", returnStdout: true).trim()
                }
            }
        }
        stage ('Build docker image') {
            when {
                expression { env.CHANGE_BRANCH?.startsWith('rc') }
            }
            steps {
                script {
                    def image = docker.build("${env.IMAGE_NAME}:${env.IMAGE_TAG}")
                    sh "docker tag ${env.IMAGE_NAME}:${env.IMAGE_TAG} ${env.REGISTRY_NAME}/${env.IMAGE_NAME}:${env.IMAGE_TAG}"
                }
            }
        }
        stage ('Push docker image to registry') {
            when {
                expression { env.CHANGE_BRANCH?.startsWith('rc') }
            }
            steps {
                script {
                    docker.withRegistry('https://registry.entcor/harbor/', 'harbor-credentials-id') {
                        docker.image("${env.REGISTRY_NAME}/${env.IMAGE_NAME}:${env.IMAGE_TAG}").push()
                    }
                }
            }
        }
    }
    post {
        always {
            script {
                echo "Cleaning up workspace..."
                sh "rm -rf ${env.WORKSPACE}/rc/ || true"
            }
        }
        success {
            script {
                if (env.CHANGE_BRANCH?.startsWith('rc')) { 
                    echo "Attempting to merge PR ${env.CHANGE_ID} into master..."
                    withCredentials([usernamePassword(credentialsId: 'gitea_creds', usernameVariable: 'GITEA_USER', passwordVariable: 'GITEA_PASS')]) {
                        def prId = env.CHANGE_ID
                        // Merge the PR
                        sh """
                        curl -X POST \
                             -u "${GITEA_USER}:${GITEA_PASS}" \
                             -H "Content-Type: application/json" \
                             -d '{"do":"merge"}' \
                             http://git.entcor/api/v1/repos/deployer3000/trust-module-frontend/pulls/${prId}/merge
                        """
                        echo "PR ${prId} merged successfully into master!"
                        // Notify Gitea with the PR status
                        notify(GITEA_USER, GITEA_PASS, GITEA_REPOSITORY_URL, "trust-module-frontend", prId, "success")
                    }
                }
            }
        }
        failure {
            echo "Pipeline failed. Check the logs for details."
        }
        aborted {
            echo "Pipeline was aborted."
        }
    }
}
