#!/bin/bash
#
# Phase 12: Networking & Gateways
# Configure ingress, DNS, SSL/TLS, WAF
#

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/config.sh"

log_info "=========================================="
log_info "Phase 12: Networking & Gateways"
log_info "=========================================="

log_warning "This phase requires manual configuration for DNS and SSL certificates"
log_info "See docs/deployment/DEPLOYMENT_GUIDE.md Phase 12 for detailed instructions"

# 12.1 Deploy Ingress Controller
log_step "12.1 Deploying NGINX Ingress Controller..."

if ! command -v helm &> /dev/null; then
  log_warning "Helm not found. Install Helm to deploy ingress controller."
else
  if ! helm list -n ingress-nginx | grep -q ingress-nginx; then
    log_info "Installing NGINX Ingress Controller..."
    helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
    helm repo update
    
    kubectl create namespace ingress-nginx --dry-run=client -o yaml | kubectl apply -f -
    helm install ingress-nginx ingress-nginx/ingress-nginx \
      --namespace ingress-nginx \
      --create-namespace \
      || log_warning "Ingress controller installation failed or already exists"
  else
    log_success "Ingress controller already installed"
  fi
fi

# 12.2 Apply Ingress Resources
log_step "12.2 Applying ingress resources..."

INGRESS_FILE="${K8S_DIR}/base/ingress.yaml"
if [ -f "${INGRESS_FILE}" ]; then
  kubectl apply -f "${INGRESS_FILE}" -n "${NAMESPACE}" || log_warning "Failed to apply ingress"
  log_success "Ingress resources applied"
else
  log_warning "Ingress configuration not found at ${INGRESS_FILE}"
  log_info "Create ingress.yaml in ${K8S_DIR}/base/"
fi

# 12.3 Install cert-manager (for Let's Encrypt)
log_step "12.3 Installing cert-manager..."

if ! kubectl get crd certificates.cert-manager.io &> /dev/null; then
  log_info "Installing cert-manager..."
  kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.13.0/cert-manager.yaml || \
    log_warning "Failed to install cert-manager"
  
  log_info "Waiting for cert-manager to be ready..."
  kubectl wait --for=condition=ready pod \
    -l app.kubernetes.io/instance=cert-manager \
    -n cert-manager \
    --timeout=300s || log_warning "cert-manager not ready yet"
else
  log_success "cert-manager already installed"
fi

log_info "Networking configuration complete"
log_info "Next steps (manual):"
log_info "  1. Configure DNS records"
log_info "  2. Create ClusterIssuer for Let's Encrypt"
log_info "  3. Configure WAF rules (if using Application Gateway)"

# Save state
save_state "phase12" "complete"

log_success "=========================================="
log_success "Phase 12: Networking & Gateways - COMPLETE"
log_success "=========================================="

