#!/bin/bash
# Deploy Identity Service with Entra VerifiedID to Staging
# This script automates the staging deployment

set -euo pipefail

GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

cd "$(dirname "$0")/../.."

# Check prerequisites
log_info "Checking prerequisites..."

if ! command -v kubectl &> /dev/null; then
    log_error "kubectl not found. Please install kubectl"
    exit 1
fi

if ! kubectl cluster-info &> /dev/null; then
    log_error "Not connected to Kubernetes cluster"
    exit 1
fi

# Check if namespace exists
NAMESPACE="the-order-staging"
if ! kubectl get namespace "${NAMESPACE}" &> /dev/null; then
    log_info "Creating namespace: ${NAMESPACE}"
    kubectl create namespace "${NAMESPACE}"
fi

# Check if secrets exist
log_info "Checking for Entra secrets..."
if ! kubectl get secret entra-verifiedid-secrets -n "${NAMESPACE}" &> /dev/null; then
    log_warning "Entra secrets not found. Creating from template..."
    log_info "Please update infra/k8s/identity-service-entra-secrets.yaml with actual values"
    read -p "Press Enter after updating secrets file..."
    kubectl apply -f infra/k8s/identity-service-entra-secrets.yaml -n "${NAMESPACE}"
else
    log_success "Secrets found"
fi

# Build and push image (if needed)
log_info "Building Docker image..."
IMAGE_TAG="${IMAGE_TAG:-staging-$(date +%Y%m%d-%H%M%S)}"
IMAGE_NAME="ghcr.io/the-order/identity-service:${IMAGE_TAG}"

if [ "${BUILD_IMAGE:-true}" = "true" ]; then
    log_info "Building image: ${IMAGE_NAME}"
    docker build -t "${IMAGE_NAME}" -f services/identity/Dockerfile .
    docker push "${IMAGE_NAME}"
    log_success "Image built and pushed"
else
    log_info "Skipping image build (set BUILD_IMAGE=false to skip)"
fi

# Update deployment with image tag
log_info "Updating deployment manifest..."
sed "s|ghcr.io/the-order/identity-service:latest|${IMAGE_NAME}|g" \
    infra/k8s/identity-service-deployment-entra.yaml > /tmp/identity-deployment-staging.yaml

# Apply deployment
log_info "Deploying to staging..."
kubectl apply -f /tmp/identity-deployment-staging.yaml -n "${NAMESPACE}"

# Wait for deployment
log_info "Waiting for deployment to be ready..."
kubectl rollout status deployment/identity-service -n "${NAMESPACE}" --timeout=5m

# Verify deployment
log_info "Verifying deployment..."
if kubectl get deployment identity-service -n "${NAMESPACE}" &> /dev/null; then
    REPLICAS=$(kubectl get deployment identity-service -n "${NAMESPACE}" -o jsonpath='{.status.readyReplicas}')
    DESIRED=$(kubectl get deployment identity-service -n "${NAMESPACE}" -o jsonpath='{.spec.replicas}')
    
    if [ "${REPLICAS}" = "${DESIRED}" ]; then
        log_success "Deployment successful! ${REPLICAS}/${DESIRED} replicas ready"
    else
        log_warning "Deployment in progress: ${REPLICAS}/${DESIRED} replicas ready"
    fi
fi

# Check service health
log_info "Checking service health..."
SERVICE_URL=$(kubectl get ingress identity-service-ingress -n "${NAMESPACE}" -o jsonpath='{.spec.rules[0].host}' 2>/dev/null || echo "")
if [ -n "${SERVICE_URL}" ]; then
    log_info "Service URL: https://${SERVICE_URL}"
    log_info "Testing health endpoint..."
    sleep 5
    if curl -sf "https://${SERVICE_URL}/health" > /dev/null; then
        log_success "Service is healthy!"
    else
        log_warning "Health check failed (service may still be starting)"
    fi
fi

# Display logs
log_info "Recent logs:"
kubectl logs -n "${NAMESPACE}" deployment/identity-service --tail=20 | grep -i entra || log_info "No Entra-related logs yet"

log_success "Staging deployment complete!"
log_info "Next steps:"
echo "1. Configure webhook URL in Entra VerifiedID: https://api-staging.theorder.org/vc/entra/webhook"
echo "2. Test credential issuance"
echo "3. Verify metrics collection"
echo "4. Check logs: kubectl logs -n ${NAMESPACE} deployment/identity-service -f"

