def deploy() {
    node('ubuntu') {
        try {
            stage('Checkout (Ubuntu)') {
                checkout scm
            }

            stage('Setup Node.js (Ubuntu)') {
                nodejs(nodeJSInstallationName: 'Node23') {
                    sh 'node -v'
                    sh 'pnpm -v'
                }
            }

            stage('Install Dependencies (Ubuntu)') {
                nodejs(nodeJSInstallationName: 'Node23') {
                    sh 'pnpm install --frozen-lockfile --production=false'
                }
            }

            stage('Build (Ubuntu)') {
                nodejs(nodeJSInstallationName: 'Node23') {
                    sh 'NODE_ENV=production pnpm build:cloudflare'
                }
            }

            stage('Deploy (Ubuntu)') {
                nodejs(nodeJSInstallationName: 'Node23') {
                    // Deploy to Cloudflare Pages using wrangler
                    withCredentials([string(credentialsId: 'cloudflare-api-token', variable: 'CLOUDFLARE_API_TOKEN')]) {
                        sh 'pnpm wrangler pages deploy build --branch main'
                    }
                }
            }
        } finally {
            cleanWs()
        }
    }
}

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/**/farmcontrol-*.dmg, app_dist/**/farmcontrol-*.exe, app_dist/**/farmcontrol-*.pkg, app_dist/**/farmcontrol-*.msi', fingerprint: true
            }
        }
    }
}

def setBuildNameFromPackageVersion() {
    node('ubuntu') {
        stage('Set Build Name') {
            checkout scm
            def version
            nodejs(nodeJSInstallationName: 'Node23') {
                version = sh(
                    script: "node -p \"require('./package.json').version\"",
                    returnStdout: true
                ).trim()
            }
            currentBuild.displayName = "${version}"
            echo "Build name set to package.json version: ${version}"
        }
    }
}

try {
    setBuildNameFromPackageVersion()

    parallel(
        'Windows Build': buildOnLabel('windows', 'pnpm build:electron'),
        'MacOS Build': buildOnLabel('macos', 'pnpm build:electron'),
        'Ubuntu Deploy': { deploy() }
    )

    echo 'All parallel stages completed successfully!'

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