// Jenkinsfile for Python Microservices Project

pipeline {
    agent any

    environment {
        // Define the Docker registry to push images to.
        // Replace with your actual Docker registry (e.g., your-docker-hub-username or ECR/GCR registry)
        DOCKER_REGISTRY = 'your-docker-registry'
        // Define the Docker image tag. Using BUILD_NUMBER for unique tags.
        DOCKER_IMAGE_TAG = "${env.BUILD_NUMBER}"
        // SonarQube server configuration (replace 'sonarqube-server' with your SonarQube server name in Jenkins)
        // SONAR_SCANNER_HOME = tool 'SonarScanner' // Assumes SonarScanner is configured as a tool in Jenkins
    }

    stages {
        stage('Unit Tests') {
            steps {
                script {
                    // Run unit tests for each service
                    def services = ['user-service-py', 'product-service-py', 'order-service-py', 'notification-service-py']
                    for (int i = 0; i < services.size(); i++) {
                        def service = services[i]
                        dir(service) {
                            echo "Running unit tests for ${service}..."
                            // Install dependencies for testing
                            sh 'pip install -r requirements.txt'
                            // Run unit tests using unittest (or pytest if installed)
                            sh 'python -m unittest discover'
                        }
                    }
                }
            }
        }

        stage('SonarQube Analysis') {
            steps {
                script {
                    // Perform SonarQube analysis for each service
                    // The 'withSonarQubeEnv' step injects SonarQube server details (URL, credentials)
                    // Assumes a SonarQube server is configured in Jenkins with the name 'sonarqube-server'
                    withSonarQubeEnv(credentialsId: 'sonarqube-token', scannerHome: 'SONAR_SCANNER_HOME') { // Replace 'sonarqube-token' with your actual SonarQube token credential ID
                        def services = ['user-service-py', 'product-service-py', 'order-service-py', 'notification-service-py']
                        for (int i = 0; i < services.size(); i++) {
                            def service = services[i]
                            dir(service) {
                                echo "Running SonarQube analysis for ${service}..."
                                // 'catchError' ensures the pipeline continues even if SonarQube quality gate fails
                                // The build will be marked as UNSTABLE in case of quality gate failure.
                                catchError(buildResult: 'UNSTABLE', stageResult: 'UNSTABLE') {
                                    // For Python, you typically run sonar-scanner directly.
                                    // Ensure sonar-scanner is installed and configured on the Jenkins agent.
                                    sh "sonar-scanner -Dsonar.projectKey=${service} -Dsonar.projectName=${service}"
                                }
                            }
                        }
                    }
                }
            }
        }

        stage('Build Docker Images') {
            steps {
                script {
                    // Build Docker images for all Python services using the Makefile
                    echo "Building Docker images for Python services..."
                    sh 'make docker-build DOCKER_REGISTRY=${DOCKER_REGISTRY} DOCKER_IMAGE_TAG=${DOCKER_IMAGE_TAG}'
                }
            }
        }

        stage('Push Docker Images') {
            steps {
                script {
                    // Push all Docker images to the registry
                    echo "Pushing Docker images for Python services..."
                    sh 'make docker-push DOCKER_REGISTRY=${DOCKER_REGISTRY} DOCKER_IMAGE_TAG=${DOCKER_IMAGE_TAG}'
                }
            }
        }

        stage('Deploy to Kubernetes') {
            steps {
                script {
                    // This stage assumes you have kubectl configured and connected to a Kubernetes cluster.
                    // It will apply the Kubernetes manifests for each service.
                    echo "Deploying Python microservices to Kubernetes..."
                    sh 'make k8s-deploy'
                    echo "Deployment to Kubernetes complete."
                }
            }
        }
    }

    post {
        always {
            echo "Pipeline finished."
        }
        failure {
            echo "Pipeline failed. Check logs for errors."
        }
        unstable {
            echo "Pipeline finished with UNSTABLE status (e.g., SonarQube quality gate failed)."
        }
        success {
            echo "Pipeline finished successfully."
        }
    }
}
