pipeline {
    agent any

    environment {
        NODE_VERSION = '22'
        NVM_DIR      = "$HOME/.nvm"
    }

    stages {
        stage('Setup Node.js') {
            steps {
                sh '''
                    if ! command -v node &> /dev/null; then
                        curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
                        . "$NVM_DIR/nvm.sh"
                        nvm install $NODE_VERSION
                        nvm use $NODE_VERSION
                    fi
                    . "$NVM_DIR/nvm.sh"
                    node -v
                    npm install -g pnpm@10
                    pnpm -v
                '''
            }
        }

        stage('Install') {
            steps {
                sh '''
                    . "$NVM_DIR/nvm.sh"
                    pnpm install --frozen-lockfile
                '''
            }
        }

        stage('Build') {
            steps {
                sh '''
                    . "$NVM_DIR/nvm.sh"
                    pnpm run build:antd
                '''
            }
        }

        stage('Archive') {
            steps {
                archiveArtifacts artifacts: 'apps/web-antd/dist/**', allowEmptyArchive: true, fingerprint: true
            }
        }
    }

    post {
        success {
            echo 'Frontend build succeeded!'
        }
        failure {
            echo 'Frontend build failed!'
        }
        always {
            deleteDir()
        }
    }
}
