pipeline {
    agent any

    environment {
        REGISTRY = "docker.rri.co.id"
        IMAGE_NAME = "ci3-app"
        IMAGE_TAG = "latest"
        KUBE_NAMESPACE = "default"
        GIT_CREDENTIALS_ID = "1138e92b-d38f-4578-9058-82fc7b6f734b"
        DOCKER_CREDENTIALS_ID = "docker-credentials"
    }

    stages {

        stage('Checkout Source Code') {
            steps {
                echo 'Cloning source code from Gitea...'
                git branch: 'main',
                    credentialsId: "${GIT_CREDENTIALS_ID}",
                    url: 'https://git.rri.co.id/admin/ci3-app.git'
            }
        }

        stage('Build Docker Image') {
            steps {
                echo 'Building Docker Image...'
                sh "docker build -t ${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG} ."
            }
        }

        stage('Push Docker Image to Registry') {
            steps {
                echo 'Pushing Docker Image to Local Registry...'
                withCredentials([string(credentialsId: "${DOCKER_CREDENTIALS_ID}", variable: 'DOCKER_PASS')]) {
                    sh """
                    echo \$DOCKER_PASS | docker login ${REGISTRY} -u admin --password-stdin
                    docker push ${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}
                    """
                }
            }
        }

        stage('Deploy to Kubernetes') {
            steps {
                echo 'Applying Kubernetes YAML Manifests...'
                sh """
                kubectl apply -f k8s/ci3-nginx-configmap.yaml
                kubectl apply -f k8s/ci3-deployment.yaml
                kubectl apply -f k8s/mysql-deployment.yaml
                kubectl apply -f k8s/phpmyadmin-deployment.yaml
                kubectl apply -f k8s/ci3-service.yaml
                kubectl apply -f k8s/mysql-service.yaml
                kubectl apply -f k8s/phpmyadmin-service.yaml
                """
            }
        }

        stage('Verify Deployment') {
            steps {
                echo 'Checking Pods Status...'
                sh "kubectl get pods -n ${KUBE_NAMESPACE} --selector=app=ci3-app"
                sh "kubectl get pods -n ${KUBE_NAMESPACE} --selector=app=mysql"
                sh "kubectl get pods -n ${KUBE_NAMESPACE} --selector=app=phpmyadmin"
            }
        }
    }

    post {
        success {
            echo 'Deployment Successful!'
        }
        failure {
            echo 'Deployment Failed. Please Check Jenkins Logs.'
        }
    }
}
