pipeline {
    agent any

    environment {
        // Defines the output directory for the published application
        DOTNET_PUBLISH_DIR = 'publish'
    }

    stages {
        stage('Restore Dependencies') {
            steps {
                echo 'Restoring NuGet packages...'
                sh 'dotnet restore'
            }
        }

        stage('Build') {
            steps {
                echo 'Building the project in Release mode...'
                sh 'dotnet build --configuration Release --no-restore'
            }
        }

        stage('Test') {
            steps {
                echo 'Running tests...'
                // If you have a separate test project, specify its path
                // sh 'dotnet test YourTestProject/YourTestProject.csproj --no-build'
            }
        }

        stage('Publish') {
            steps {
                echo 'Publishing the application...'
                sh "dotnet publish --configuration Release --output ${DOTNET_PUBLISH_DIR} --no-build"
            }
        }

        stage('Deploy') {
            steps {
                echo 'Deploying to the server...'
                // This step securely copies the build output to your web server.
                // You need to configure SSH credentials in Jenkins (e.g., with ID 'my-server-credentials').
                // It then restarts your application's service.
                sshagent(credentials: ['my-server-credentials']) {
                    sh '''
                        ssh -o StrictHostKeyChecking=no root@51.195.148.156 "mkdir -p /var/www/print-server"
                        scp -r ${DOTNET_PUBLISH_DIR}/* root@51.195.148.156:/var/www/print-server/
                        ssh root@51.195.148.156 "sudo systemctl restart print-server"
                    '''
                }
            }
        }
    }

    post {
        always {
            echo 'Pipeline finished.'
            cleanWs() // Clean up the workspace
        }
    }
}