#!/bin/bash
#
# Phase 11: Frontend Applications Deployment
# Deploy portal applications to Kubernetes
#

set -euo pipefail

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

log_info "=========================================="
log_info "Phase 11: Frontend Applications Deployment"
log_info "=========================================="

# Verify Kubernetes access
if ! kubectl cluster-info &> /dev/null; then
  az aks get-credentials --resource-group "${AKS_RESOURCE_GROUP}" \
                         --name "${AKS_NAME}" \
                         --overwrite-existing
fi

# Ensure namespace exists
kubectl create namespace "${NAMESPACE}" --dry-run=client -o yaml | kubectl apply -f -

# Deploy each app
log_step "11.1 Deploying frontend applications..."

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

# Save state
save_state "phase11" "complete"

log_success "=========================================="
log_success "Phase 11: Frontend Applications - COMPLETE"
log_success "=========================================="

