pipeline {
    agent {
        kubernetes {
            yamlFile '.jenkins/podTemplate.yaml'
        }
    }
    environment {
        RESOURCE_GROUP = 'tst-aks-rg'
        CLUSTER_NAME   = 'build'
        DEPLOY_FILES   = 'namespace.yaml secret-store.yaml deploy.yaml ingress.yaml'
        NAMESPACE      = 'user-microservice'
        DEPLOYMENT     = 'api'
        CLIENT_ID      = 'c302726f-fafb-4143-94c1-67a70975574a'
    }
    stages {
        stage('Checkout') {
            steps {
                container('kubectl') {
                    checkout scm
                }
            }
        }
        stage('Login to Azure & Get Kubeconfig') {
            steps {
                container('kubectl') {
                    sh '''
                        az login --identity --client-id ${CLIENT_ID}
                        az aks get-credentials --resource-group $RESOURCE_GROUP --name $CLUSTER_NAME --overwrite-existing
                        kubelogin convert-kubeconfig -l azurecli
                    '''
                }
            }
        }
        stage('Apply Kubernetes Resources') {
            steps {
                container('kubectl') {
                    script {
                        def files = DEPLOY_FILES.tokenize()
                        for (file in files) {
                            sh "kubectl apply -f ${file}"
                        }
                    }
                }
            }
        }

        stage('Verify Deployment') {
            steps {
                container('kubectl') {
                    script {
                        // Waiting until all pods reach "ready" status
                        sh '''
                            echo "Waiting for deployment rollout..."
                            kubectl rollout status deployment/$DEPLOYMENT -n $NAMESPACE --timeout=60s
                        '''
                    }
                }
            }
        }

        stage('Health Check') {
            steps {
                container('kubectl') {
                    script {
                        // Check if app is healthy
                        def ingressUrl = "https://user-microservice.marcin00.pl/health"
                        sh """
                            echo "Checking app health ${ingressUrl}..."
                            for i in {1..30}; do
                                if curl -sf $ingressUrl; then
                                    echo "Health check OK"
                                    exit 0
                                else
                                    echo "Health check failed. Retry \$i..."
                                    sleep 5
                                fi
                            done
                            echo "Health check failed."
                            exit 1
                        """
                    }
                }
            }
        }
    }
}
