pipeline {
    agent any
    environment {
        CI_PROJECT_DIR = "${WORKSPACE}"
        PATH = "${CI_PROJECT_DIR}/node_modules/.bin:$PATH"
    }
    stages {
        stage('Replace config-files ') {
            steps {
                sh 'cp -f documents_configs/dev_config apps/services/config.ts'
            }
        }

    stages {
        stage('Check Node Version') {
            steps {
                sh 'node -v'
                sh 'npm -v'
            }
        }
        stage('Install Dependencies') {
            steps {
                dir("${CI_PROJECT_DIR}") {
                    sh 'npm install --force'
                }
            }
        }
        stage('Check Nx Version') {
            steps {
                sh 'nx --version'
            }
        }
        
        stage('Build Frontend') {
            steps {
                dir("${CI_PROJECT_DIR}") {
                    sh '''
                        export PATH="${CI_PROJECT_DIR}/node_modules/.bin:$PATH"
                        npx nx run ui-masters-ui:build || true --skip-nx-cache
                    '''
                }
            }
        }
        stage('Build Backend') {
            steps {
                dir("${CI_PROJECT_DIR}") {
                    sh '''
                        export PATH="${CI_PROJECT_DIR}/node_modules/.bin:$PATH"
                        npx nx run services-masters:build --prod --skip-nx-cache
                        npx nx run services-sale-service:build --prod --skip-nx-cache
                        npx nx run services-procurement-service:build --prod --skip-nx-cache
                        npx nx run services-warehouse-service:build --prod --skip-nx-cache
                        npx nx run services-logistics:build --prod --skip-nx-cache
                        npx nx run services-transportation:build --prod --skip-nx-cache
                        npx nx run services-backend:build --prod --skip-nx-cache
                        npx nx run services-hrms:build --prod --skip-nx-cache
                        npx nx run services-production:build --prod --skip-nx-cache
                        npx nx run services-raw-material-procurement:build --prod --skip-nx-cache
                        npx nx run services-planning:build --prod --skip-nx-cache
                        npx nx run services-analytics:build --prod --skip-nx-cache
                        npx nx run services-job-management-api:build --prod --skip-nx-cache
                        npx nx run services-job-management:build --prod --skip-nx-cache
                        npx nx run services-asset-management:build --prod --skip-nx-cache
                        npx nx run services-user-logs:build --prod --skip-nx-cache
                        npx nx run services-canteen-management:build --prod --skip-nx-cache
                        npx nx run services-vms:build --prod --skip-nx-cache
                        npx nx run services-enquiry-management:build --prod --skip-nx-cache
                        npx nx run services-finance:build --prod --skip-nx-cache
                    '''
                }
            }
        }
        
        stage('Transfer Build Files') {
            steps {
                sshagent(credentials: ['1']) { // Use the correct credentials ID here
                    sh '''
                        ssh root@142.93.219.119 "rm -rf /var/www/html/dev/*"
                        ssh root@142.93.219.119 "rm -rf /var/www/html/bmr-dev/dist/apps/services"
                        scp -r ${CI_PROJECT_DIR}/dist/apps/ui/masters-ui/* root@142.93.219.119:/var/www/html/dev
                        scp -r ${CI_PROJECT_DIR}/dist/apps/services root@142.93.219.119:/var/www/html/bmr-dev/dist/apps
                    '''
                }
            }
        }
        stage('Restart Services with PM2') {
            steps {
                sshagent(credentials: ['1']) { // Use the correct credentials ID here
                    sh '''
                        ssh root@142.93.219.119 <<EOF
source ~/.bashrc
pm2 restart all
pm2 status
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."""
                )
            }
        }
    }
}
