pipeline {
    agent any

    environment {
        COMPOSE_PROJECT_NAME = 'juntete-deploy'
    }

    stages {
        stage('Build Images') {
            steps {
                echo 'Building Docker images...'
                sh '''
                    cd ${WORKSPACE}
                    docker compose -f docker-compose.production.yml build --no-cache
                '''
            }
        }

        stage('Stop Old Containers') {
            steps {
                echo 'Stopping old containers...'
                sh '''
                    cd ${WORKSPACE}
                    docker compose -f docker-compose.production.yml down || true
                '''
            }
        }

        stage('Start New Containers') {
            steps {
                echo 'Starting new containers...'
                sh '''
                    cd ${WORKSPACE}
                    docker compose -f docker-compose.production.yml up -d
                '''
            }
        }

        stage('Wait for Startup') {
            steps {
                echo 'Waiting for services to initialize...'
                sh '''
                    # Wait for services to start
                    sleep 30
                '''
            }
        }

        stage('Health Check') {
            steps {
                echo 'Running health checks...'
                sh '''
                    # Check if containers are running
                    echo "Checking container status..."
                    docker ps | grep juntete

                    # Check backend health
                    echo "Checking backend health..."
                    wget -q --spider http://localhost:8000/health || echo "Backend health check failed (might still be starting)"

                    # Check frontend (correct port is 3000)
                    echo "Checking frontend health..."
                    wget -q --spider http://localhost:3000/juntete || echo "Frontend health check failed (might still be starting)"

                    echo "Deployment completed!"
                '''
            }
        }
    }

    post {
        always {
            echo 'Pipeline execution completed'
            sh '''
                cd ${WORKSPACE}
                echo "Container status:"
                docker compose -f docker-compose.production.yml ps || true

                echo "Recent logs (backend):"
                docker compose -f docker-compose.production.yml logs --tail=20 backend || true

                echo "Recent logs (frontend):"
                docker compose -f docker-compose.production.yml logs --tail=20 frontend || true
            '''
        }
        success {
            echo 'Deployment successful!'
        }
        failure {
            echo 'Deployment failed. Check logs above.'
        }
    }
}