pipeline {
    agent any

    environment {
        IMAGE_NAME = "helloworldapp"
        IMAGE_TAG = "${env.BUILD_NUMBER ?: 'latest'}"
        DOCKER_REGISTRY = "192.168.50.221:5000" // replace with your registry e.g. docker.io/yourorg
        DOCKER_CREDENTIALS_ID = "dockerhub-credentials" // set this credential in Jenkins
    }

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

        stage('Build') {
            steps {
                dir('HelloWorldApp') {
                    sh 'dotnet restore'
                    sh 'dotnet build --configuration Release --no-restore'
                }
            }
        }

        stage('Test') {
            steps {
                sh 'dotnet test HelloWorld.slnx --configuration Release --no-restore --verbosity minimal'
            }
        }

        stage('Docker Build') {
            steps {
                dir('HelloWorldApp') {
                    sh "docker build -t ${DOCKER_REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG} ."
                }
            }
        }

        stage('Docker Push') {
            steps {
                withCredentials([usernamePassword(credentialsId: DOCKER_CREDENTIALS_ID, usernameVariable: 'REGISTRY_USER', passwordVariable: 'REGISTRY_PASSWORD')]) {
                    sh 'echo $REGISTRY_PASSWORD | docker login ${DOCKER_REGISTRY} -u $REGISTRY_USER --password-stdin'
                    sh "docker push ${DOCKER_REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}"
                }
            }
        }

        stage('Deploy') {
            steps {
                echo "Docker image pushed to ${DOCKER_REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}. Deploy to your Docker host as needed."
            }
        }
    }

    post {
        always {
            cleanWs()
        }
    }
}
