pipeline {
    agent any
    environment {
        SRC     = '/opt/zioinfo/src'
        JAR_DIR = '/opt/zioinfo/app'
        STATIC  = '/var/www/zioinfo'
        MVN     = '/usr/bin/mvn'
        NOTIFY  = "${ITSM_BASE_URL}/api/messenger/webhook"
    }
    options {
        buildDiscarder(logRotator(numToKeepStr: '5'))
        timeout(time: 20, unit: 'MINUTES')
        timestamps()
    }
    stages {
        stage('Checkout') {
            steps {
                checkout([
                    $class: 'GitSCM', branches: scm.branches,
                    userRemoteConfigs: scm.userRemoteConfigs,
                    extensions: [[$class: 'SparseCheckoutPaths',
                        sparseCheckoutPaths: [[path: 'frontend'], [path: 'backend']]
                    ]]
                ])
            }
        }
        stage('Frontend Build') {
            steps {
                dir('frontend') {
                    sh 'npm ci --legacy-peer-deps --prefer-offline 2>/dev/null || npm install --legacy-peer-deps'
                    sh 'npm run build'
                }
            }
        }
        stage('Backend Build') {
            steps {
                dir('backend') {
                    sh "${MVN} clean package -DskipTests -q"
                }
            }
        }
        stage('Deploy') {
            when { branch 'main' }
            steps {
                sh """
                    cp backend/target/*.jar ${JAR_DIR}/app.jar
                    cp -r backend/src/main/resources/static/. ${STATIC}/
                    systemctl restart zioinfo
                    sleep 4
                    systemctl is-active zioinfo || exit 1
                """
            }
        }
    }
    post {
        success { sh "curl -sf -X POST ${NOTIFY} -H 'Content-Type:application/json' -d '{\"event\":\"build_result\",\"room\":\"ops\",\"success\":true,\"result_summary\":\"✅ zioinfo-web 배포 완료 #${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\":\"❌ zioinfo-web 빌드 실패 #${BUILD_NUMBER}\"}' 2>/dev/null || true" }
    }
}