pipeline {
    agent any

    environment {
        DEPLOY_PATH = '/opt/solution/public'
        BACKUP_PATH = '/opt/solution/public_backup'
        HEALTH_URL  = 'http://solution.zioinfo.co.kr'
    }

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

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

        stage('Test') {
            steps {
                sh 'npm test -- --watchAll=false --passWithNoTests || true'
            }
        }

        stage('Deploy') {
            when { branch 'main' }
            steps {
                sh "cp -r ${DEPLOY_PATH} ${BACKUP_PATH} 2>/dev/null || true"
                sh "rsync -a --delete dist/ ${DEPLOY_PATH}/"
                sh 'systemctl reload nginx'
            }
        }

        stage('Smoke Test') {
            when { branch 'main' }
            steps {
                sh "curl -sf ${HEALTH_URL} | grep -q 'GUARDiA' && echo '[PASS] 배포 성공' || (echo '[FAIL] smoke test 실패'; exit 1)"
            }
        }
    }

    post {
        failure {
            echo '배포 실패 — 백업으로 롤백'
            sh "cp -r ${BACKUP_PATH}/ ${DEPLOY_PATH}/ 2>/dev/null || true"
            sh 'systemctl reload nginx 2>/dev/null || true'
        }
        success {
            echo '✓ solution.zioinfo.co.kr 배포 완료'
        }
    }
}
