pipeline {
    agent any

    environment {
        NODE_VERSION = '20.12.2'  // Ensure this version exists in NVM
    }

    stages {
        stage('Checkout') {
            steps {
                script {
                    checkout([
                        $class: 'GitSCM',
                        branches: [[name: '*/master']],
                        userRemoteConfigs: [[
                            url: 'https://github.com/Prakhar19999/NammaNiruBackend.git',
                            credentialsId: 'github-https'
                        ]]
                    ])
                }
            }
        }

        stage('Setup Node.js') {
            steps {
                bat '''
                echo Using Node.js version: %NODE_VERSION%
                call nvm install %NODE_VERSION%
                call nvm use %NODE_VERSION%
                node -v
                npm -v
                '''
            }
        }

        stage('Install Dependencies') {
            steps {
                bat '''
                cd nammaniru_common_service
                call npm install
                '''
            }
        }

        stage('Build') {
            steps {
                bat '''
                cd nammaniru_common_service
                npm run build
                '''
            }
        }

        stage('Publish') {
            steps {
                withCredentials([string(credentialsId: 'npm-auth-token', variable: 'NPM_AUTH_TOKEN')]) {
                    bat """
                echo //registry.npmjs.org/:_authToken=${NPM_AUTH_TOKEN} > %prakh%\\.npmrc
                cd nammaniru_common_service
                npm publish
                """
                }
            }
        }
    }
}