pipeline {
    agent any

    environment {
        HARBOR        = 'harbor.myriadcara.com'
        IMAGE         = 'harbor.myriadcara.com/vaishnavi-ecommerce/admin'
        VERSION_FILE  = '/home/jenkins/vaishnavi-admin-version.txt'
    }

    stages {

        stage('Generate Tag') {
            steps {
                script {
                    def version
                    if (fileExists(VERSION_FILE)) {
                        version = readFile(VERSION_FILE).trim()
                    } else {
                        version = '1.0.0'
                    }
                    def parts = version.tokenize('.')
                    def major = parts[0].toInteger()
                    def minor = parts[1].toInteger()
                    def patch = parts[2].toInteger() + 1
                    def newVersion = "${major}.${minor}.${patch}"
                    writeFile file: VERSION_FILE, text: newVersion
                    env.TAG = newVersion
                    echo "🏷️  New image tag: v${env.TAG}"
                }
            }
        }

        stage('Build Image') {
            steps {
                sh """
                    docker build \
                        --provenance=false \
                        --sbom=false \
                        -t ${IMAGE}:${env.TAG} \
                        -t ${IMAGE}:latest \
                        --label build-number=${env.BUILD_NUMBER} \
                        --label version=${env.TAG} \
                        .
                """
            }
        }

        stage('Push to Harbor') {
            steps {
                withCredentials([usernamePassword(
                    credentialsId: 'harbor-creds',
                    usernameVariable: 'HARBOR_USER',
                    passwordVariable: 'HARBOR_PASS'
                )]) {
                    sh """
                        echo "\$HARBOR_PASS" | docker login https://${HARBOR} -u "\$HARBOR_USER" --password-stdin
                        docker push ${IMAGE}:${env.TAG}
                        docker push ${IMAGE}:latest
                    """
                }
            }
        }
    }

    post {
        always {
            sh "docker rmi ${IMAGE}:${env.TAG} || true"
            sh "docker rmi ${IMAGE}:latest || true"
        }
        success {
            echo "✅ Successfully pushed: ${IMAGE}:${env.TAG}"
        }
        failure {
            echo "❌ Pipeline failed at tag: ${env.TAG}"
        }
    }
}