def buildOnLabel(label, buildCommand) {
    return {
        node(label) {
            stage("Checkout (${label})") {
                checkout scm
            }

            stage("Setup Node.js (${label})") {
                nodejs(nodeJSInstallationName: 'Node23') {
                    if (isUnix()) {
                        sh 'node -v'
                        sh 'pnpm -v'
                    } else {
                        bat 'node -v'
                        bat 'pnpm -v'
                    }
                }
            }

            stage("Install Dependencies (${label})") {
                nodejs(nodeJSInstallationName: 'Node23') {
                    if (isUnix()) {
                        sh 'pnpm install --frozen-lockfile --production=false'
                    } else {
                        bat 'pnpm install --frozen-lockfile --production=false'
                    }
                }
            }

            stage("Build (${label})") {
                nodejs(nodeJSInstallationName: 'Node23') {
                    if (isUnix()) {
                        sh "NODE_ENV=production ${buildCommand}"
                    } else {
                        bat "set NODE_ENV=production && ${buildCommand}"
                    }
                }
            }

            stage("Archive Artifacts (${label})") {
                archiveArtifacts artifacts: 'app_dist/**/*.dmg, app_dist/**/*.exe, app_dist/**/*.AppImage, app_dist/**/*.deb, app_dist/**/*.rpm', fingerprint: true
            }
        }
    }
}

def buildLinuxWithBun() {
    return {
        node('ubuntu') {
            stage("Checkout (Linux)") {
                checkout scm
            }

            stage("Setup Bun (Linux)") {
                sh '''
                    curl -fsSL https://bun.sh/install | bash
                    export PATH="$HOME/.bun/bin:$PATH"
                    bun --version
                '''
            }

            stage("Install Dependencies (Linux)") {
                sh '''
                    export PATH="$HOME/.bun/bin:$PATH"
                    bun install --frozen-lockfile
                '''
            }

            stage("Build (Linux)") {
                sh '''
                    export PATH="$HOME/.bun/bin:$PATH"
                    NODE_ENV=production bun run build:linux
                '''
            }

            stage("Archive Artifacts (Linux)") {
                archiveArtifacts artifacts: 'app_dist/**/*.deb, app_dist/**/*.rpm', fingerprint: true
            }
        }
    }
}

try {
    parallel(
        'Windows Build': buildOnLabel('windows', 'pnpm build:electron'),
        'MacOS Build': buildOnLabel('macos', 'pnpm build:electron'),
        'Linux Build': buildLinuxWithBun()
    )

    echo 'All parallel stages completed successfully!'

} catch (Exception e) {
    echo "Pipeline failed: ${e.message}"
    throw e
}
