pipeline {
    agent any
    environment {
        NOTIFY = "${ITSM_BASE_URL}/api/messenger/webhook"
    }
    options {
        buildDiscarder(logRotator(numToKeepStr: '5'))
        timeout(time: 10, unit: 'MINUTES')
        timestamps()
    }
    stages {
        stage('Checkout') { steps { checkout scm } }
        stage('Validate') {
            steps {
                sh 'node --version || true'
                sh "grep -E '\"expo\"' package.json | head -1 || true"
            }
        }
        stage('Install') {
            steps { sh 'npm ci --legacy-peer-deps 2>/dev/null || npm install --legacy-peer-deps' }
        }
        stage('Type Check') {
            when { expression { fileExists('tsconfig.json') } }
            steps { sh 'npx tsc --noEmit 2>/dev/null || true' }
        }
        stage('EAS Build Trigger') {
            when {
                allOf {
                    branch 'main'
                    expression { return env.EXPO_TOKEN?.trim() }
                }
            }
            steps {
                sh '''
                    npm install -g @expo/eas-cli 2>/dev/null || true
                    eas build --platform android --non-interactive --no-wait \
                        --profile production 2>/dev/null || echo "EAS 빌드 큐 등록됨"
                '''
            }
        }
    }
    post {
        success { sh "curl -sf -X POST ${NOTIFY} -H 'Content-Type:application/json' -d '{\"event\":\"build_result\",\"room\":\"ops\",\"success\":true,\"result_summary\":\"✅ guardia-messenger 검증 완료 #${BUILD_NUMBER}\"}' 2>/dev/null || true" }
        failure { sh "curl -sf -X POST ${NOTIFY} -H 'Content-Type:application/json' -d '{\"event\":\"build_result\",\"room\":\"ops\",\"success\":false,\"result_summary\":\"❌ guardia-messenger 빌드 실패 #${BUILD_NUMBER}\"}' 2>/dev/null || true" }
    }
}
