pipeline {
    agent {
        docker {
            image 'hashicorp/terraform:latest'
            args '--entrypoint="" -u root --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_URL      = "http://floci:4566"
        
        PROJECT_ROOT          = "/var/jenkins_home/workspace/${env.JOB_NAME}"
        TERRAFORM_DIR         = "${PROJECT_ROOT}/terraform/environments/test"
        ACCOUNT_ID            = "000000000000"
    }

    stages {
        stage('00_checkout') {
            steps {
                echo "========================================"
                echo "SACC v4 - Destruccion de Infraestructura"
                echo "========================================"
                
                checkout([
                    $class: 'GitSCM',
                    branches: [[name: '*/main']],
                    userRemoteConfigs: [[
                        url: 'http://gitea:3000/evert/iac-duplicate.git',
                        credentialsId: 'gitea-credentials'
                    ]]
                ])
                
                sh """
                    echo "[INFO] Repositorio clonado"
                """
            }
        }

        stage('01_confirm_destruction') {
            steps {
                echo "========================================"
                echo "CONFIRMACION DE DESTRUCCION"
                echo "========================================"
                
                sh """
                    echo "⚠️  ATENCION: ESTA ACCION ES IRREVERSIBLE"
                    echo "Se destruiran todos los recursos del entorno TEST"
                    echo ""
                    echo "Recursos afectados:"
                    echo "  - Instancia EC2"
                    echo "  - Base de datos RDS"
                    echo "  - Bucket S3"
                    echo "  - Distribucion CloudFront"
                    echo "  - VPC, Security Groups, etc."
                    echo ""
                    echo "Para confirmar, ejecutar este pipeline con parametro:"
                    echo "  CONFIRM_DESTROY = 'DESTRUIR'"
                """
                
                script {
                    if (params.CONFIRM_DESTROY != 'DESTRUIR') {
                        error("Destruccion no confirmada. Establecer CONFIRM_DESTROY='DESTRUIR'")
                    }
                }
            }
        }

        stage('02_backup_rds') {
            steps {
                echo "========================================"
                echo "PASO 2: Backup de RDS"
                echo "========================================"
                
                sh """
                    echo "[INFO] Creando snapshot final..."
                    aws --endpoint-url=${AWS_ENDPOINT_URL} rds create-db-snapshot \
                        --db-instance-identifier sacc4-test-db-prod \
                        --db-snapshot-identifier sacc4-test-final-\$(date +%Y%m%d-%H%M%S) \
                        --region ${AWS_DEFAULT_REGION} || echo "[WARN] No se pudo crear snapshot"
                    
                    echo "[OK] Backup completado"
                """
            }
        }

        stage('03_cleanup_s3') {
            steps {
                echo "========================================"
                echo "PASO 3: Limpiando S3"
                echo "========================================"
                
                sh """
                    echo "[INFO] Vaciando bucket S3..."
                    aws --endpoint-url=${AWS_ENDPOINT_URL} s3 rm s3://sacc4-frontend-test-ccsoft --recursive 2>/dev/null || true
                    
                    echo "[OK] S3 limpiado"
                """
            }
        }

        stage('04_terraform_destroy') {
            steps {
                echo "========================================"
                echo "PASO 4: Terraform Destroy"
                echo "========================================"
                
                sh """
                    cd ${TERRAFORM_DIR}
                    
                    echo "[INFO] Inicializando Terraform..."
                    terraform init \
                        -backend-config="bucket=sacc4-terraform-state-test-${ACCOUNT_ID}" \
                        -backend-config="key=sacc4-test/terraform.tfstate" \
                        -backend-config="region=${AWS_DEFAULT_REGION}" \
                        -backend-config="endpoint=${AWS_ENDPOINT_URL}" \
                        -backend-config="dynamodb_endpoint=${AWS_ENDPOINT_URL}" \
                        -backend-config="dynamodb_table=sacc4-terraform-locks-test-${ACCOUNT_ID}" \
                        -backend-config="skip_credentials_validation=true" \
                        -backend-config="skip_metadata_api_check=true" \
                        -backend-config="skip_region_validation=true" \
                        -backend-config="skip_requesting_account_id=true" \
                        -backend-config="use_path_style=true"
                    
                    echo "[INFO] Destruyendo infraestructura..."
                    terraform destroy -auto-approve
                    
                    echo "[OK] Terraform destroy completado"
                """
            }
        }

        stage('05_cleanup_state') {
            steps {
                echo "========================================"
                echo "PASO 5: Limpiando estado Terraform"
                echo "========================================"
                
                sh """
                    echo "[INFO] Eliminando bucket de estado..."
                    aws --endpoint-url=${AWS_ENDPOINT_URL} s3 rm s3://sacc4-terraform-state-test-${ACCOUNT_ID} --recursive 2>/dev/null || true
                    aws --endpoint-url=${AWS_ENDPOINT_URL} s3api delete-bucket \
                        --bucket sacc4-terraform-state-test-${ACCOUNT_ID} \
                        --region ${AWS_DEFAULT_REGION} 2>/dev/null || true
                    
                    echo "[INFO] Eliminando tabla DynamoDB..."
                    aws --endpoint-url=${AWS_ENDPOINT_URL} dynamodb delete-table \
                        --table-name sacc4-terraform-locks-test-${ACCOUNT_ID} \
                        --region ${AWS_DEFAULT_REGION} 2>/dev/null || true
                    
                    echo "[OK] Estado eliminado"
                """
            }
        }

        stage('06_verify_destruction') {
            steps {
                echo "========================================"
                echo "PASO 6: Verificando destruccion"
                echo "========================================"
                
                sh """
                    echo "[INFO] Verificando recursos eliminados..."
                    
                    echo "Buckets S3 restantes:"
                    aws --endpoint-url=${AWS_ENDPOINT_URL} s3 ls
                    
                    echo ""
                    echo "Tablas DynamoDB restantes:"
                    aws --endpoint-url=${AWS_ENDPOINT_URL} dynamodb list-tables
                    
                    echo ""
                    echo "Instancias EC2 restantes:"
                    aws --endpoint-url=${AWS_ENDPOINT_URL} ec2 describe-instances \
                        --query 'Reservations[*].Instances[*].InstanceId' \
                        --output text
                    
                    echo "[OK] Verificacion completada"
                """
            }
        }
    }

    post {
        always {
            echo "========================================"
            echo "Pipeline de destruccion finalizado"
            echo "========================================"
        }
        success {
            echo "✅ ENTORNO DESTRUIDO EXITOSAMENTE"
        }
        failure {
            echo "❌ ERROR EN LA DESTRUCCION"
        }
    }
}
