pipeline {
    agent any

    environment {
        // Jenkins 容器内路径（docker-compose 已挂载 ./nginx/html:/web_deploy）
        DEPLOY_PATH = '/web_deploy/alien_website/'
        NODE_VERSION = '20'
    }

    options {
        buildDiscarder(logRotator(numToKeepStr: '10'))
        timeout(time: 30, unit: 'MINUTES')
        timestamps()
    }

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

        stage('Install & Build') {
            steps {
                sh '''
                    set -e

                    export NVM_DIR="$HOME/.nvm"
                    if [ ! -s "$NVM_DIR/nvm.sh" ]; then
                        echo "安装 nvm..."
                        curl -fsSL https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
                    fi
                    . "$NVM_DIR/nvm.sh"

                    nvm install ${NODE_VERSION}
                    nvm use ${NODE_VERSION}

                    node -v
                    npm -v
                    npm ci
                    npm run build
                '''
            }
        }

        stage('Deploy') {
            steps {
                sh '''
                    set -e

                    if [ ! -d dist ]; then
                        echo "错误: dist 目录不存在，构建可能失败"
                        exit 1
                    fi

                    if [ ! -d "${DEPLOY_PATH}" ] && [ ! -d /web_deploy ]; then
                        echo "错误: /web_deploy 未挂载，请检查 docker-compose 中 jenkins volumes 配置"
                        echo "  - ./nginx/html:/web_deploy"
                        exit 1
                    fi

                    echo "开始本地部署到 ${DEPLOY_PATH}"

                    mkdir -p "${DEPLOY_PATH}"
                    find "${DEPLOY_PATH}" -mindepth 1 -exec rm -rf {} +
                    cp -a dist/. "${DEPLOY_PATH}/"

                    echo "部署完成"
                '''
            }
        }
    }

    post {
        success {
            echo "网站已成功部署至 ${DEPLOY_PATH}"
        }
        failure {
            echo '部署失败，请查看上方日志'
        }
        always {
            cleanWs()
        }
    }
}
