pipeline {
    agent any

    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }

        stage('Build and Create Docker Image') {
            steps {
                script {
                    def branchName = BRANCH_NAME
                    def imageName

                    echo branchName;

                    if (branchName == 'dev') {
                        imageName = 'sulemantalpur6/frontend:dev${BUILD_NUMBER}'
                    } else if (branchName == 'master') {
                        imageName = 'sulemantalpur6/frontend:master${BUILD_NUMBER}'
                    } else if (branchName == 'QA') {
                        imageName = 'sulemantalpur6/frontend:QA${BUILD_NUMBER}'
                    } else if (branchName == 'UAT') {
                        imageName = 'sulemantalpur6/frontend:UAT${BUILD_NUMBER}'
                    } else {
                        echo "Branch $branchName not configured for Docker image build."
                        currentBuild.result = 'FAILURE'
                        return
                    }

                    sh 'npm install'
                    sh 'npm run build'
                    sh "docker build -t $imageName ."
                }
            }
        }

        stage('Push Docker Image to Docker Hub') {
            steps {
                script {
                    def branchName = BRANCH_NAME
                    def buildNumber = BUILD_NUMBER

                    if (branchName == 'dev' || branchName == 'master'  || branchName == 'QA' || branchName == 'UAT') {
                        withCredentials([usernamePassword(credentialsId: 'dockerHub', usernameVariable: 'DOCKER_HUB_USERNAME', passwordVariable: 'DOCKER_HUB_PASSWORD')]) {
                            sh "docker login -u $DOCKER_HUB_USERNAME -p $DOCKER_HUB_PASSWORD"
                            sh "docker push sulemantalpur6/frontend:$branchName$buildNumber"
                        }
                    }
                }
            }
        }
    }
}
