// Build, test and release pipeline for the storefront service.
//
// Parameters reach shell steps only through the environment: every sh step
// below is single-quoted, so the shell expands "$IMAGE_TAG" as data and
// Groovy never splices a parameter into command text.

@Library('platform-pipeline@v4.2.0') _

pipeline {
    agent { label 'linux && docker' }

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

    parameters {
        string(name: 'IMAGE_TAG', defaultValue: '', description: 'Image tag to release (empty: commit SHA)')
        choice(name: 'TARGET', choices: ['staging', 'production'], description: 'Where to deploy')
        booleanParam(name: 'RUN_E2E', defaultValue: true, description: 'Run the browser tests')
        booleanParam(name: 'DRY_RUN', defaultValue: false, description: 'Render manifests only')
    }

    environment {
        REGISTRY = 'registry.example.com/storefront'
        GRADLE_OPTS = '-Dorg.gradle.daemon=false'
        DOCKER_LOGIN = credentials('registry-robot')
    }

    stages {
        stage('Checkout') {
            steps {
                checkout scm
                script {
                    env.GIT_SHORT = sh(script: 'git rev-parse --short=12 HEAD', returnStdout: true).trim()
                    currentBuild.displayName = "#${env.BUILD_NUMBER} ${env.GIT_SHORT}"
                }
            }
        }

        stage('Build') {
            steps {
                sh './gradlew --no-daemon clean build -x test'
                sh "./gradlew --no-daemon -PbuildNumber=${env.BUILD_NUMBER} assemble"
            }
        }

        stage('Unit tests') {
            steps {
                sh './gradlew --no-daemon test'
            }
            post {
                always {
                    junit testResults: 'build/test-results/test/*.xml', allowEmptyResults: false
                }
            }
        }

        stage('Browser tests') {
            when { expression { params.RUN_E2E } }
            steps {
                sh "./scripts/e2e.sh --headless=true --retries=${params.RUN_E2E ? 2 : 0}"
            }
        }

        stage('Image') {
            steps {
                sh '''
                    set -eu
                    tag="${IMAGE_TAG:-$GIT_SHORT}"
                    echo "$DOCKER_LOGIN_PSW" | docker login --username "$DOCKER_LOGIN_USR" --password-stdin registry.example.com
                    docker build --pull -t "$REGISTRY:$tag" .
                    docker push "$REGISTRY:$tag"
                '''
            }
        }

        stage('Deploy') {
            when {
                anyOf {
                    branch 'main'
                    expression { params.TARGET == 'staging' }
                }
            }
            steps {
                withCredentials([file(credentialsId: 'kubeconfig-storefront', variable: 'KUBECONFIG')]) {
                    sh 'kubectl --kubeconfig "$KUBECONFIG" config current-context'
                    sh './deploy/render.sh "$TARGET" "${IMAGE_TAG:-$GIT_SHORT}" > rendered.yaml'
                    script {
                        if (params.DRY_RUN) {
                            echo "Dry run: manifests for ${params.TARGET} rendered, nothing applied"
                        } else {
                            sh 'kubectl --kubeconfig "$KUBECONFIG" apply -f rendered.yaml'
                        }
                    }
                }
            }
        }

        stage('Notify') {
            steps {
                withCredentials([string(credentialsId: 'chat-webhook', variable: 'WEBHOOK_URL')]) {
                    sh '''
                        curl -fsS -X POST -H 'Content-Type: application/json' \
                            --data "{\\"text\\": \\"storefront $BUILD_NUMBER deployed to $TARGET\\"}" \
                            "$WEBHOOK_URL"
                    '''
                }
            }
        }
    }

    post {
        success {
            echo "Released ${params.IMAGE_TAG ?: env.GIT_SHORT} to ${params.TARGET}"
        }
        failure {
            echo "Build ${env.BUILD_URL} failed on ${env.NODE_NAME}"
        }
        cleanup {
            sh 'docker logout registry.example.com || true'
            cleanWs()
        }
    }
}
