pipeline {
    agent any

    environment {
        APP_NAME   = 'zioinfo-esn'
        DEPLOY_DIR = '/opt/zioinfo-esn/src'
        SERVICE    = 'zioinfo-esn'
        JAR_NAME   = 'esn.jar'
    }

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

        stage('Build Frontend') {
            steps {
                dir('frontend') {
                    sh 'npm ci'
                    sh 'npm run build'
                }
            }
        }

        stage('Build Backend') {
            steps {
                dir('backend') {
                    sh 'mvn clean package -DskipTests -q'
                }
            }
        }

        stage('Deploy') {
            steps {
                sh """
                    sudo systemctl stop ${SERVICE} || true
                    sudo mkdir -p ${DEPLOY_DIR}/backend/target
                    sudo cp backend/target/${JAR_NAME} ${DEPLOY_DIR}/backend/target/${JAR_NAME}
                    sudo systemctl start ${SERVICE}
                """
            }
        }

        stage('Health Check') {
            steps {
                sh """
                    sleep 15
                    curl -sf http://localhost:8015/actuator/health | grep -q UP || exit 1
                """
            }
        }
    }

    post {
        success {
            echo "zioinfo-esn 배포 성공"
        }
        failure {
            echo "zioinfo-esn 배포 실패 — 롤백 필요"
        }
    }
}
