pipeline {
    agent any

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

    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()
                    env.PUBLISH_VERSION = bat(script: '@node -p "require(\'./package.json\').version"', returnStdout: true).trim()
                }
            }
        }

        stage('Build Info') {
            steps {
                echo "发布版本: ${env.PUBLISH_VERSION}  ⚠ 发布前请确认已在 package.json 中更新版本号"
                echo "Git Commit: ${env.GIT_COMMIT_SHORT}"
            }
        }

        stage('Install Dependencies') {
            steps {
                withCredentials([usernamePassword(credentialsId: 'NEXUS_CREDS', passwordVariable: 'NPM_PASS', usernameVariable: 'NPM_USER')]) {
                    bat """
                        powershell -NonInteractive -Command "\$auth=[Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(\$env:NPM_USER+':'+\$env:NPM_PASS)); @('@xuqm:registry=https://nexus.xuqinmin.com/repository/npm-hosted/','//nexus.xuqinmin.com/repository/npm-hosted/:_auth='+\$auth) | Set-Content .npmrc"
                        npm install --legacy-peer-deps
                    """
                }
            }
        }

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

        stage('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') {
            steps {
                withCredentials([usernamePassword(credentialsId: 'NEXUS_CREDS', passwordVariable: 'NPM_PASS', usernameVariable: 'NPM_USER')]) {
                    bat """
                        powershell -NonInteractive -Command "\$auth=[Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(\$env:NPM_USER+':'+\$env:NPM_PASS)); @('@xuqm:registry=https://nexus.xuqinmin.com/repository/npm-hosted/','//nexus.xuqinmin.com/repository/npm-hosted/:_auth='+\$auth) | Set-Content .npmrc"
                        npm publish --workspaces --registry %NEXUS_REGISTRY%
                    """
                }
            }
            post {
                always {
                    bat 'del .npmrc 2>nul || exit 0'
                }
            }
        }
    }

    post {
        success {
            echo "RN SDK v${env.PUBLISH_VERSION} 构建成功 (Commit: ${env.GIT_COMMIT_SHORT})"
        }
        failure {
            echo "RN SDK 构建失败，请检查日志"
        }
    }
}
