@Library('trustmodule-shared-libraries') _

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 {
                    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 dockerUtils = new com.trustmodule.docker.DockerUtils(pipeline)
                    dockerUtils.buildImage(env.IMAGE_NAME, env.IMAGE_TAG)
                    dockerUtils.tagImage(env.IMAGE_NAME, env.IMAGE_TAG, env.REGISTRY_NAME)
                }
            }
        }

        stage('Push Docker image to registry') {
            when {
                expression { env.CHANGE_BRANCH?.startsWith('rc') }
            }
            steps {
                script {
                    def dockerUtils = new com.trustmodule.docker.DockerUtils(pipeline)
                    dockerUtils.pushImageToRegistry(env.IMAGE_NAME, env.IMAGE_TAG, env.REGISTRY_NAME, 'https://registry.entcor/harbor/', 'harbor-credentials-id')
                }
            }
        }
    }

    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
                        def giteaUtils = new com.trustmodule.gitea.GiteaUtils(pipeline)
                        giteaUtils.merge(GITEA_USER, GITEA_PASS, GITEA_REPOSITORY_URL, 'deployer3000/trust-module-frontend', prId)
                        echo "PR ${prId} merged successfully into master!"
                        giteaUtils.notify(GITEA_USER, GITEA_PASS, GITEA_REPOSITORY_URL, 'deployer3000/trust-module-frontend', prId, 'sucess')
                    }
                }
            }
        }
        failure {
            echo "Pipeline failed. Check the logs for details."
        }
        aborted {
            echo "Pipeline was aborted."
        }
    }
}
