#!/bin/bash
#
# Phase 10: Backend Services Deployment
# Deploy backend services to Kubernetes
#

set -euo pipefail

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

log_info "=========================================="
log_info "Phase 10: Backend Services Deployment"
log_info "=========================================="

# Verify Kubernetes access
log_step "10.1 Verifying Kubernetes access..."

if ! kubectl cluster-info &> /dev/null; then
  log_info "Getting AKS credentials..."
  az aks get-credentials --resource-group "${AKS_RESOURCE_GROUP}" \
                         --name "${AKS_NAME}" \
                         --overwrite-existing \
    || error_exit "Failed to get AKS credentials"
fi

kubectl cluster-info || error_exit "Kubernetes cluster not accessible"

# Ensure namespace exists
log_step "10.2 Ensuring namespace exists..."

kubectl create namespace "${NAMESPACE}" --dry-run=client -o yaml | kubectl apply -f - || \
  log_warning "Namespace may already exist"

# Deploy External Secrets (if not already deployed)
log_step "10.3 Checking External Secrets Operator..."

if ! kubectl get crd externalsecrets.external-secrets.io &> /dev/null; then
  log_info "Installing External Secrets Operator..."
  kubectl apply -f https://external-secrets.io/latest/deploy/ || error_exit "Failed to install External Secrets"
  
  log_info "Waiting for External Secrets Operator to be ready..."
  kubectl wait --for=condition=ready pod \
    -l app.kubernetes.io/name=external-secrets \
    -n external-secrets-system \
    --timeout=300s || log_warning "External Secrets Operator not ready yet"
else
  log_success "External Secrets Operator already installed"
fi

# Deploy each service
log_step "10.4 Deploying backend services..."

for service in "${SERVICES[@]}"; do
  log_info "Deploying ${service} service..."
  
  # Check if manifests exist
  SERVICE_DIR="${K8S_DIR}/base/${service}"
  if [ ! -d "${SERVICE_DIR}" ]; then
    log_warning "Kubernetes manifests not found for ${service} at ${SERVICE_DIR}"
    log_info "Skipping ${service} deployment"
    continue
  fi
  
  # Apply manifests
  kubectl apply -f "${SERVICE_DIR}" -n "${NAMESPACE}" || error_exit "Failed to deploy ${service}"
  
  # Wait for deployment
  log_info "Waiting for ${service} deployment..."
  kubectl wait --for=condition=available \
    deployment/"${service}" \
    -n "${NAMESPACE}" \
    --timeout=300s || log_warning "${service} deployment not ready yet"
  
  # Verify pods
  PODS=$(kubectl get pods -l app="${service}" -n "${NAMESPACE}" --no-headers 2>/dev/null | wc -l)
  if [ "${PODS}" -gt 0 ]; then
    log_success "${service} deployed (${PODS} pod(s))"
    
    # Check pod status
    kubectl get pods -l app="${service}" -n "${NAMESPACE}"
  else
    log_warning "${service} pods not found"
  fi
done

# Verify service endpoints
log_step "10.5 Verifying service endpoints..."

for service in "${SERVICES[@]}"; do
  if kubectl get svc "${service}" -n "${NAMESPACE}" &> /dev/null; then
    log_success "Service ${service} endpoint created"
    
    # Test health endpoint (if accessible)
    PORT="${SERVICE_PORTS[$service]}"
    if [ -n "${PORT}" ]; then
      log_info "Testing ${service} health endpoint on port ${PORT}..."
      kubectl run test-${service}-health \
        --image=curlimages/curl \
        --rm -i --restart=Never \
        -- curl -f "http://${service}:${PORT}/health" \
        -n "${NAMESPACE}" 2>/dev/null && \
        log_success "${service} health check passed" || \
        log_warning "${service} health check failed or endpoint not ready"
    fi
  else
    log_warning "Service ${service} endpoint not found"
  fi
done

# Save state
save_state "phase10" "complete"

log_success "=========================================="
log_success "Phase 10: Backend Services - COMPLETE"
log_success "=========================================="

