pipeline {
    agent any

    options {
        timestamps()
        timeout(time: 1, unit: 'HOURS')
        buildDiscarder(logRotator(numToKeepStr: '10'))
    }

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

        stage('Detect Branch & Deploy') {
            steps {
                script {
                    def branch = env.GIT_BRANCH ?: 'unknown'
                    echo "📌 Current branch: ${branch}"

                    if (branch.contains('develop')) {
                        echo "🚀 Deploying to DEV environment..."
                        sh '/root/deploy-dev.sh'
                    } else if (branch.contains('master') || branch.contains('main')) {
                        echo "🚀 Deploying to PROD environment..."
                        sh '/root/deploy-prod.sh'
                    } else {
                        echo "⚠️  Branch ${branch} is not configured for deployment. Skipping..."
                        currentBuild.result = 'SUCCESS'
                    }
                }
            }
        }
    }

    post {
        success {
            echo "✅ Pipeline selesai - Deploy berhasil!"
        }
        failure {
            echo "❌ Pipeline gagal - Cek logs di atas"
        }
    }
}
