pipeline {
    agent any

    stages {
        stage('Checkout SCM') {
            steps {
                checkout([$class: 'GitSCM', branches: [[name: '**']],
                          doGenerateSubmoduleConfigurations: false, 
                          extensions: [], 
                          userRemoteConfigs: [[url: 'http://192.168.10.95:3002/Ismail/nodeMap', credentialsId: 'gmail2']]])
            }
        }
        stage('Check Node.js Version') {
            steps {
                script {
                    def nodeVersion = sh(script: 'node --version', returnStdout: true).trim()
                    echo "Node.js version: ${nodeVersion}"
                }
            }
        }
        stage('Install Dependencies') {
            steps {
                sh 'npm install'
            }
        }
        stage('Run Unit Tests') {
            steps {
                sh 'npm test'
            }
        }
        stage('Run Cypress Tests') {
            steps {
                script {
                    echo "Installing Cypress..."
                    sh 'npx cypress install'

                    echo "Running Cypress Tests..."
                    try {
                        sh 'npx cypress run --reporter spec'
                    } catch (err) {
                        echo "Cypress Tests Failed!"
                        error "Build failed due to Cypress test failures."
                    }

                    echo "Cypress Tests Completed."
                }
            }
        }
    }

    post {
        success {
            emailext(
                subject: "Build Success: ${JOB_NAME} #${BUILD_NUMBER}",
                body: """
                Build Successful! Details:
                - Job Name: ${JOB_NAME}
                - Build Number: ${BUILD_NUMBER}
                - Build URL: ${BUILD_URL}
                """,
                to: "ismailali1553@gmail.com"
            )
        }
        failure {
            emailext(
                subject: "Build Failed: ${JOB_NAME} #${BUILD_NUMBER}",
                body: """
                Build Failed! Details:
                - Job Name: ${JOB_NAME}
                - Build Number: ${BUILD_NUMBER}
                - Build URL: ${BUILD_URL}
                """,
                to: "ismailali1553@gmail.com"
            )
        }
    }
}
