pipeline {
    agent any

    environment {
        TEST_SERVER = '54.156.92.54'
        UAT_SERVER  = '54.156.92.54'
        PROD_SERVER = '54.156.92.54'

        // SCP-style paths (IMPORTANT)
        APP_PATH_WINDOWS_TEST = '/C:/Apps/logisticsapitest'
        APP_PATH_WINDOWS_UAT  = '/C:/Apps/logisticsapiuat'
        APP_PATH_WINDOWS_PROD = '/C:/Apps/logisticsapi'
    }

    stages {

        stage('Checkout Code') {
            steps {
                git branch: 'main',
                    credentialsId: 'JENKID',
                    url: 'git@bitbucket.org:tvikla/logisticsapp.git'
            }
        }

        stage('Deploy to Test') {
            steps {
                deployEnv(TEST_SERVER, APP_PATH_WINDOWS_TEST)
            }
        }

        stage('Deploy to UAT') {
            steps {
                timeout(time: 5, unit: 'MINUTES') {
                    input message: 'Approve deployment to UAT?'
                }
                deployEnv(UAT_SERVER, APP_PATH_WINDOWS_UAT)
            }
        }

        stage('Deploy to Production') {
            steps {
                timeout(time: 10, unit: 'MINUTES') {
                    input message: 'Approve deployment to Production?'
                }
                deployEnv(PROD_SERVER, APP_PATH_WINDOWS_PROD)
            }
        }
    }

    post {
        success {
            emailext(
                to: 'support@tvikla.com',
                subject: "SUCCESS: ${currentBuild.fullDisplayName}",
                body: 'The pipeline has completed successfully.'
            )
        }
        failure {
            emailext(
                to: 'support@tvikla.com',
                subject: "FAILURE: ${currentBuild.fullDisplayName}",
                body: 'The pipeline has failed. Please check Jenkins logs.'
            )
        }
    }
}

/* ======================================================
   SSH-KEY BASED DEPLOY (NO sshpass, NO passwords)
   ====================================================== */
def deployEnv(server, scpPath) {
    sshagent(credentials: ['WIN_SSH_KEY']) {

        // Convert /C:/Apps/... → C:\Apps\...
        def psPath = scpPath
            .replaceFirst('^/([A-Za-z]):', '$1:')
            .replace('/', '\\')

        sh """
            set -e
            echo "Deploying logisticsapp to $server:$psPath"

            echo "Ensuring target directory exists..."
            ssh -o StrictHostKeyChecking=no Administrator@$server \\
              "powershell -NoProfile -Command \\
                \\"if (!(Test-Path '${psPath}')) { \\
                      New-Item -ItemType Directory -Path '${psPath}' | Out-Null \\
                  }\\""

            echo "Copying application files..."
            scp -o StrictHostKeyChecking=no -r ./* Administrator@$server:${scpPath}
        """
    }
}