pipeline {
    agent any

    environment {
        REGISTRY = 'git.virtheart.com'
        REGISTRY_OWNER = 'virtheart'
        IMAGE_NAME = "${env.JOB_NAME.replaceAll(/[^a-zA-Z0-9.-]/, '-').toLowerCase()}"
        IMAGE_TAG = 'latest'
        CONTAINER_PORT = '3000'
        HOST_PORT = '3010'
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }

        stage('Build Image') {
            steps {
                script {
                    def imageFullName = "${REGISTRY}/${REGISTRY_OWNER}/${IMAGE_NAME}:${IMAGE_TAG}"
                    sh "docker build -t ${imageFullName} ."
                }
            }
        }

        stage('Push Image') {
            steps {
                withCredentials([usernamePassword(credentialsId: 'docker-registry-credentials', usernameVariable: 'REGISTRY_USERNAME', passwordVariable: 'REGISTRY_PASSWORD')]) {
                    script {
                        def imageFullName = "${REGISTRY}/${REGISTRY_OWNER}/${IMAGE_NAME}:${IMAGE_TAG}"
                        sh '''
                            set +x
                            echo $REGISTRY_PASSWORD | docker login $REGISTRY -u $REGISTRY_USERNAME --password-stdin
                            docker push ''' + imageFullName
                    }
                }
            }
        }

        stage('Deploy Container') {
            steps {
                script {
                    def imageFullName = "${REGISTRY}/${REGISTRY_OWNER}/${IMAGE_NAME}:${IMAGE_TAG}"
                    sh """
                        docker stop $IMAGE_NAME || true
                        docker rm $IMAGE_NAME || true
                        docker pull $imageFullName
                        docker run -d --name $IMAGE_NAME \
                            -p $HOST_PORT:$CONTAINER_PORT \
                            --restart unless-stopped \
                            $imageFullName
                    """
                }
            }
        }
    }

    post {
        always {
            cleanWs()
        }
    }
}