pipeline {
    agent {
        docker {
            image 'amazon/aws-cli:latest'
            args  '-u root --entrypoint="" --network ci-network -v /var/run/docker.sock:/var/run/docker.sock'
        }
    }

    environment {
        AWS_ACCESS_KEY_ID     = "000000000000"
        AWS_SECRET_ACCESS_KEY = "test"
        AWS_DEFAULT_REGION    = "us-east-1"
        AWS_ENDPOINT          = "http://floci:4566"
        APP_NAME = "demo-app"
        REGISTRY = "172.16.20.100:5000"
    }

    stages {
        stage('Analisis de Calidad') {
            steps {
                echo "Simulando analisis con SonarQube..."
                withSonarQubeEnv('SonarLocal') {
                    echo "Enviando metricas a SonarQube (simulado)"
                }
            }
        }

        stage('Construccion y Empaquetado') {
            steps {
                echo "Construyendo imagen Docker..."
                sh '''
                cat > Dockerfile <<'DOCKER'
FROM nginx:alpine
RUN echo "Hola desde Floci" > /usr/share/nginx/html/index.html
DOCKER
                '''
                sh "docker build -t \${REGISTRY}/\${APP_NAME}:latest ."
            }
        }

        stage('Publicar en Registry Local') {
            steps {
                echo "Subiendo artefacto..."
                sh "docker push \${REGISTRY}/\${APP_NAME}:latest"
                echo "Imagen publicada."
            }
        }

        stage('Despliegue en Infraestructura (Floci AWS)') {
            steps {
                echo "Desplegando en AWS emulado..."
                sh 'aws --endpoint-url=\${AWS_ENDPOINT} s3 mb s3://\${APP_NAME}-bucket || true'
                sh 'echo "Configuracion de produccion" > config.json'
                sh 'aws --endpoint-url=\${AWS_ENDPOINT} s3 cp config.json s3://\${APP_NAME}-bucket/'
                sh 'aws --endpoint-url=\${AWS_ENDPOINT} s3 ls s3://\${APP_NAME}-bucket/'
            }
        }
    }

    post {
        always {
            echo "Pipeline finalizado."
        }
    }
}
