pipeline {
    agent any

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

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

        stage('Build Frontend') {
            steps {
                dir('frontend') {
                    sh 'npm ci --legacy-peer-deps'
                    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}
                    sudo cp backend/target/${JAR_NAME} ${DEPLOY_DIR}/app.jar
                    sudo systemctl start ${SERVICE}
                """
            }
        }

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

    post {
        success {
            echo "guardia-esn 배포 성공"
        }
        failure {
            sh "sudo systemctl stop ${SERVICE} || true"
            echo "guardia-esn 배포 실패"
        }
    }
}
