pipeline {
    agent any

    options {
        timestamps()
        timeout(time: 1, unit: 'HOURS')
        buildDiscarder(logRotator(numToKeepStr: '10'))
    }

    parameters {
        booleanParam(name: 'DEPLOY_TO_STAGING', defaultValue: false, description: 'Deploy to staging')
        booleanParam(name: 'DEPLOY_TO_PRODUCTION', defaultValue: false, description: 'Deploy to production')
    }

    environment {
        // Docker registry configuration
        REGISTRY = credentials('docker-registry-url')
        REGISTRY_USER = credentials('docker-registry-user')
        REGISTRY_PASSWORD = credentials('docker-registry-password')
        DOCKER_IMAGE = "${REGISTRY}/${GIT_COMMIT.take(8)}"
        DOCKER_IMAGE_LATEST = "${REGISTRY}:latest"

        // Database configuration for builds
        DB_URL = "jdbc:postgresql://postgres:5432/mtgsearch_build"
        DB_USER = "postgres"
        DB_PASSWORD = "postgres"
        POSTGRES_DB = "mtgsearch_build"

        // SonarQube configuration
        SONAR_USER_HOME = "${WORKSPACE}/.sonar"
        GIT_DEPTH = "0"

        // Build cache
        GRADLE_USER_HOME = "${WORKSPACE}/.gradle"
    }

    stages {
        stage('Build Java & Frontend') {
            agent any
            steps {
                script {
                    echo "Building Java and Frontend..."
                }
                sh '''
                    chmod +x ./gradlew
                    ./gradlew clean build -x test --build-cache
                '''
            }
            post {
                success {
                    archiveArtifacts artifacts: 'backend/build/libs/**/*.jar,frontend/dist/**/*', fingerprint: true
                }
            }
        }

        stage('Run Unit Tests') {
            agent any
            steps {
                script {
                    echo "Running unit tests..."
                }
                sh '''
                    chmod +x ./gradlew
                    ./gradlew test --build-cache
                '''
            }
            post {
                always {
                    junit 'backend/build/test-results/test/**/*.xml'
                }
            }
        }

        stage('Run Integration Tests') {
            agent {
                docker {
                    image 'eclipse-temurin:21-jdk'
                    args '--network=host'
                }
            }
            when {
                anyOf {
                    branch 'main'
                    branch 'develop'
                  any       echo "Running integration tests..."
                }
                sh '''
                    chmod +x ./gradlew
                    ./gradlew integrationTest --build-cache
                '''
            }
            post {
                always {
                    junit 'backend/build/test-results/integrationTest/**/*.xml'
                }
            }
        }

        stage('Code Quality Checks') {
            agent {
                docker {
                    image 'eclipse-temurin:21-jdk'
                    args '--network=host'
                }
            }any   script {
                    echo "Running code quality checks..."
                }
                sh '''
                    chmod +x ./gradlew
                    ./gradlew check -x test
                '''
            }
            post {
                failure {
                    echo "Quality checks failed - continuing pipeline with warning"
                }
            }
        }

        stage('SonarQube Analysis') {
            agent {
                docker {
                    image 'gradle:9.4.1-jdk21-jammy'
                    args '--network=host'
                }
            }
            when {
                anyOf {
                    changeRequest()
                    branch 'main'
                  any
            when {
                anyOf {
                    changeRequest()
                    branch 'main'
                    branch 'master'
                    branch 'develop'
                }
            }
            steps {
                script {
                    echo "Running SonarQube analysis..."
                }
                withSonarQubeEnv('SonarQube') {
                    sh '''
                        chmod +x ./gradlew
                        ./gradlew sonar
                    ''{
            agent {
                docker {
                    image 'docker:latest'
                    args '-v /var/run/docker.sock:/var/run/docker.sock'
                }
            }
            when {
                anyOf {
                    branch 'main'
                    branch 'develop'
                    branch 'master'
                    buildingTag()
                }
            }
            steps {
                script {
                    echo "Building Docker image..."
                }
                sh '''
                    docker login -u ${REGISTRY_USER} -p ${REGISTRY_PASSWORD} ${REGISTRY}
                    docker build -t ${DOCKER_IMAGE} .
                    docker push ${DOCKER_IMAGE}
                    docker tag ${DOCKER_IMAGE} ${DOCKER_IMAGE_LATEST}
                    docker push ${DOCKER_IMAGE_LATEST}
                    docker logout ${REGISTRY}
                '''
            }
        }

        stage('Deploy to Staging') {
            when {
                allOf {
                    branch 'develop'
                    expression { params.DEPLOY_TO_STAGING == true }
                }
            }
            steps {
                script {
                    echo "Deploying to staging environment..."
                    input(id: 'DeployToStaging', message: 'Deploy to staging?', ok: 'Deploy')
                }
                sh '''
                    curl -X POST "${STAGING_DEPLOY_WEBHOOK}" \
                      -H "Content-Type: application/json" \
                      -d '{"image":"${DOCKER_IMAGE}"}'
                    echo "Deployment to staging triggered"
                '''
            }
        }

        stage('Deploy to Production') {
            when {
                anyOf {
                    allOf {
                        branch 'main'
                        expression { params.DEPLOY_TO_PRODUCTION == true }
                    }
                    buildingTag()
                }
            }
            steps {
                script {
                    echo "Deploying to production environment..."
                    input(id: 'DeployToProd', message: 'Deploy to production?', ok: 'Deploy')
                }
                sh '''
                    curl -X POST "${PROD_DEPLOY_WEBHOOK}" \
                      -H "Content-Type: application/json" \
                      -d '{"image":"${DOCKER_IMAGE}"}'
                    echo "Deployment to production triggered"
                '''
            }
        }
    }

    post {
        always {
            cleanWs()
        }
        failure {
            script {
                echo "Pipeline failed! Check logs for details."
                // You can add notification logic here
            }
        }
        success {
            script {
                echo "Pipeline completed successfully!"
                // You can add notification logic here
            }
        }
    }
}
