pipeline {
    agent { label 'built-in' }
    environment {
        DEPLOY_FRONTEND = '/mnt/h/bitforum/sources'
    }
    stages {
        stage('Install') {
            steps {
                script {
                    // package-lock.json 해시 비교해서 변경됐을 때만 재설치
                    def lockHash = sh(
                        script: 'sha256sum package-lock.json | cut -d" " -f1',
                        returnStdout: true
                    ).trim()
                    def cacheFile = '.npm-lock-hash'
                    def prevHash = fileExists(cacheFile)
                        ? readFile(cacheFile).trim()
                        : ''

                    if (lockHash != prevHash) {
                        echo "package-lock.json 변경 감지 → npm ci 실행"
                        sh 'npm ci'
                        writeFile file: cacheFile, text: lockHash
                    } else {
                        echo "package-lock.json 변경 없음 → 설치 스킵"
                    }
                }
            }
        }
        stage('Build') {
            steps {
                sh 'npm run build'
            }
        }
        stage('Deploy') {
            steps {
                sh '''
                    rsync -a --stats --delete \
                        --exclude="web.config" \
                        --exclude="ecosystem.config.js" \
                        --exclude="restart.ps1" \
                        --exclude=".env*" \
                        .next/standalone/ ${DEPLOY_FRONTEND}/
                '''
                sh 'rsync -a --stats --delete .next/static/ ${DEPLOY_FRONTEND}/.next/static/'
                sh 'rsync -a --stats --delete public/ ${DEPLOY_FRONTEND}/public/'
            }
        }
        stage('Restart Frontend') {
            agent { label 'windows-host' }
            steps {
                bat 'chcp 65001 && powershell.exe -ExecutionPolicy Bypass -File H:\\IIS\\bitforum\\restart.ps1'
            }
        }
    }
    post {
        success { echo 'Frontend deploy success!' }
        failure { echo 'Frontend deploy failed!' }
    }
}