pipeline {
    agent any
    environment {
        SRC    = '/opt/mail'
        STATIC = '/var/www/mail'
        NOTIFY = "http://127.0.0.1:9001/api/messenger/webhook"
    }
    options {
        buildDiscarder(logRotator(numToKeepStr: '5'))
        timeout(time: 20, unit: 'MINUTES')
        timestamps()
    }
    stages {
        stage('Checkout') { steps { checkout scm } }

        stage('Frontend Build') {
            steps {
                dir('frontend') {
                    sh 'npm ci --legacy-peer-deps 2>/dev/null || npm install --legacy-peer-deps'
                    sh 'npm run build'
                }
            }
        }

        stage('Deploy') {
            when {
                expression { env.GIT_BRANCH ==~ /.*main/ || env.BRANCH_NAME == 'main' }
            }
            steps {
                sh """
                    # Frontend 정적 파일
                    mkdir -p ${STATIC}
                    cp -r dist/. ${STATIC}/

                    # Backend 소스
                    rsync -a --exclude=__pycache__ --exclude=.git \
                          --exclude='*.pyc' --exclude='.env' \
                          backend/ ${SRC}/backend/

                    # 패키지 설치
                    ${SRC}/venv/bin/pip install -r backend/requirements.txt -q

                    # 서비스 재기동
                    systemctl restart zioinfo-mail
                    sleep 4
                    systemctl is-active zioinfo-mail || exit 1

                    # 헬스체크
                    curl -sf http://localhost:8026/health || 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-mail 배포 완료 #${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-mail 빌드 실패 #${BUILD_NUMBER}"}' \
              2>/dev/null || true"""
        }
    }
}
