pipeline {
    agent any
    environment {
        CI_PROJECT_DIR = "${WORKSPACE}"
        PATH = "${WORKSPACE}/node_modules/.bin:$PATH"
    }
    stages {
        stage('Install Dependencies') {
            steps {
                sh 'npm install --force'
            }
        }
        stage('Build backend') {
            steps {
                sh '''
                    nx build services-parikshit-service
                '''
            }
        }
        stage('Build frontend') {
            steps {
                sh '''
                    nx build ui
                '''
            }
        }
        stage('Transfer Build Files') {
            steps {
                sshagent(credentials: ['3']) { // Use the correct credentials ID here
                    sh '''
                        ssh root@206.189.138.212 "rm -rf /var/www/html/boiparkshit_ui/*"
                        ssh root@206.189.138.212 "rm -rf /var/www/html/boi-parkshit/dist/packages/services/*"
                        scp -r $CI_PROJECT_DIR/dist/packages/ui/* root@206.189.138.212:/var/www/html/boiparkshit_ui
                        scp -r $CI_PROJECT_DIR/dist/packages/services/* root@206.189.138.212:/var/www/html/boi-parkshit/dist/packages/services/
                    '''
                }
            }
        }
        stage('Restart Services with PM2') {
            steps {
                sshagent(credentials: ['3']) { // Use the correct credentials ID here
                    sh '''
                        ssh root@206.189.138.212 <<EOF
pm2 restart boi
pm2 save
EOF
                    '''
                }
            }
        }
    }
    post {
        success {
            script {
                def startTime = currentBuild.getStartTimeInMillis()
                def endTime = System.currentTimeMillis()
                def duration = (endTime - startTime) / 1000

                // Send success email
                emailext(
                    to: 'saikumarvardhi7799@gmail.com, rajud@schemaxtech.com, arunkumars@schemaxtech.com',
                    subject: "SUCCESS: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
                    body: """Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' was successful.
Start Time: ${new Date(startTime)}
End Time: ${new Date(endTime)}
Duration: ${duration} seconds
Check console output at ${env.BUILD_URL} to view the results."""
                )
            }
        }
        failure {
            script {
                def logFile = "${WORKSPACE}/log"
                def logContent = ""
                if (fileExists(logFile)) {
                    logContent = readFile(logFile).take(1000)
                } else {
                    logContent = "Log file not found."
                }

                // Send failure email
                emailext(
                    to: 'saikumarvardhi7799@gmail.com, rajud@schemaxtech.com, arunkumars@schemaxtech.com',
                    subject: "FAILURE: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
                    body: """Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]' failed.
Error Log:
${logContent}
Check console output at ${env.BUILD_URL} to view the results."""
                )
            }
        }
    }
}