pipeline {
    agent any

    parameters {
        string(name: 'VERSION', defaultValue: '', description: '发布版本号（留空使用 package.json 中的 version）')
        booleanParam(name: 'RUN_TESTS', defaultValue: true, description: '是否运行测试')
        booleanParam(name: 'PUBLISH', defaultValue: true, description: '是否发布到 Nexus npm 仓库')
    }

    environment {
        NEXUS_REGISTRY = 'https://nexus.xuqinmin.com/repository/npm-hosted/'
        GIT_URL        = 'https://xuqinmin.com/xuqmGroup/XuqmGroup-RNSDK.git'
        NODE_VERSION   = '22'
    }

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

    stages {
        stage('Checkout') {
            steps {
                checkout([
                  $class: 'GitSCM',
                  branches: [[name: 'main']],
                  extensions: [[$class: 'CleanBeforeCheckout']],
                  userRemoteConfigs: scm.userRemoteConfigs
                ])
                script {
                    env.GIT_COMMIT_SHORT = bat(script: 'git rev-parse --short HEAD', returnStdout: true).trim()
                    if (params.VERSION?.trim()) {
                        bat "npm version ${params.VERSION} --no-git-tag-version"
                    }
                    env.PUBLISH_VERSION = bat(script: 'node -p "require(\\"./package.json\\").version"', returnStdout: true).trim()
                }
            }
        }

        stage('Build Info') {
            steps {
                echo "发布版本: ${env.PUBLISH_VERSION}"
                echo "Git Commit: ${env.GIT_COMMIT_SHORT}"
            }
        }

        stage('Install Dependencies') {
            steps {
                withCredentials([usernamePassword(credentialsId: 'NEXUS_CREDS', passwordVariable: 'NPM_PASS', usernameVariable: 'NPM_USER')]) {
                    script {
                        def auth = "${NPM_USER}:${NPM_PASS}".bytes.encodeBase64().toString()
                        writeFile file: '.npmrc', text: "@xuqm:registry=https://nexus.xuqinmin.com/repository/npm-hosted/\n//nexus.xuqinmin.com/repository/npm-hosted/:_auth=${auth}\n"
                        bat 'npm install --legacy-peer-deps'
                    }
                }
            }
        }

        stage('Type Check') {
            steps {
                bat 'npm run typecheck:all || ver>nul'
            }
        }

        stage('Tests') {
            when { expression { return params.RUN_TESTS } }
            steps {
                bat 'npm test > test-results.txt 2>&1 || ver>nul'
            }
            post {
                always {
                    archiveArtifacts artifacts: 'test-results.txt', allowEmptyArchive: true
                }
            }
        }

        stage('Publish to Nexus') {
            when {
                expression { return params.PUBLISH }
            }
            steps {
                withCredentials([usernamePassword(credentialsId: 'NEXUS_CREDS', passwordVariable: 'NPM_PASS', usernameVariable: 'NPM_USER')]) {
                    script {
                        def auth = "${NPM_USER}:${NPM_PASS}".bytes.encodeBase64().toString()
                        writeFile file: '.npmrc', text: "@xuqm:registry=https://nexus.xuqinmin.com/repository/npm-hosted/\n//nexus.xuqinmin.com/repository/npm-hosted/:_auth=${auth}\n"
                        bat "npm publish --workspaces --registry %NEXUS_REGISTRY%"
                    }
                }
            }
        }
    }

    post {
        success {
            script {
                echo "RN SDK v${env.PUBLISH_VERSION} 构建成功 (Commit: ${env.GIT_COMMIT_SHORT})"
                if (params.PUBLISH) {
                    echo "已发布到 Nexus npm 仓库: ${NEXUS_REGISTRY}"
                }
            }
        }
        failure {
            echo "RN SDK 构建失败，请检查日志"
        }
        always {
            bat 'npm config delete registry 2>nul || ver>nul'
        }
    }
}
