#!/bin/bash
# EN: Quick deploy script for local Kubernetes (Docker Desktop)
# VI: Script deploy nhanh cho local Kubernetes (Docker Desktop)

set -e  # Exit on error

echo "🚀 IAM Service - Local Kubernetes Deployment"
echo "=============================================="
echo ""

# Check if kubectl is installed
if ! command -v kubectl &> /dev/null; then
    echo "❌ kubectl not found. Please install kubectl first."
    echo "   Install: brew install kubectl"
    exit 1
fi

# Check if Kubernetes is running
if ! kubectl cluster-info &> /dev/null; then
    echo "❌ Kubernetes cluster not accessible."
    echo "   Please enable Kubernetes in Docker Desktop:"
    echo "   Settings → Kubernetes → Enable Kubernetes"
    exit 1
fi

echo "✅ kubectl installed"
echo "✅ Kubernetes cluster accessible"
echo ""

# Create namespace
echo "📦 Creating namespace 'iam-local'..."
kubectl create namespace iam-local --dry-run=client -o yaml | kubectl apply -f -

# Set context
kubectl config set-context --current --namespace=iam-local

echo "✅ Namespace created and set as default"
echo ""

# Prompt for database URL
echo "🔐 Setting up secrets..."
read -p "Enter your Neon DATABASE_URL: " DATABASE_URL

if [ -z "$DATABASE_URL" ]; then
    echo "❌ DATABASE_URL is required"
    exit 1
fi

# Generate secrets
echo "🔑 Generating JWT secrets..."
JWT_SECRET=$(openssl rand -base64 32)
JWT_REFRESH_SECRET=$(openssl rand -base64 32)
JWT_ID_SECRET=$(openssl rand -base64 32)
ENCRYPTION_KEY=$(openssl rand -hex 32)

# Create secret
kubectl create secret generic iam-service-secrets \
  --from-literal=jwt-secret="$JWT_SECRET" \
  --from-literal=jwt-refresh-secret="$JWT_REFRESH_SECRET" \
  --from-literal=jwt-id-secret="$JWT_ID_SECRET" \
  --from-literal=encryption-key="$ENCRYPTION_KEY" \
  --from-literal=database-url="$DATABASE_URL" \
  --dry-run=client -o yaml | kubectl apply -f -

echo "✅ Secrets created"
echo ""

# Apply ConfigMap
echo "⚙️  Applying ConfigMap..."
kubectl apply -f iam-service-configmap.yaml

echo "✅ ConfigMap applied"
echo ""

# Build Docker image
echo "🐳 Building Docker image..."
cd ../../..
docker build -t iam-service:local -f services/iam-service/Dockerfile .
cd deployments/local/kubernetes

echo "✅ Docker image built"
echo ""

# Apply Deployment
echo "🚀 Deploying IAM Service..."
kubectl apply -f iam-service-deployment.yaml

echo "✅ Deployment created"
echo ""

# Apply Service
echo "🌐 Creating Service..."
kubectl apply -f iam-service-service.yaml

echo "✅ Service created"
echo ""

# Wait for deployment
echo "⏳ Waiting for deployment to be ready..."
kubectl wait --for=condition=available --timeout=120s deployment/iam-service

echo "✅ Deployment ready!"
echo ""

# Get service info
echo "📊 Service Information:"
kubectl get svc iam-service
echo ""

# Get pod info
echo "📦 Pod Information:"
kubectl get pods -l app=iam-service
echo ""

# Show logs
echo "📝 Recent logs:"
kubectl logs -l app=iam-service --tail=20
echo ""

echo "✅ Deployment complete!"
echo ""
echo "🎯 Next steps:"
echo "   1. Run migrations: DATABASE_URL='$DATABASE_URL' pnpm --filter @goodgo/iam-service prisma:deploy"
echo "   2. Test health: kubectl port-forward svc/iam-service 5001:80"
echo "   3. Access API: curl http://localhost:5001/health/live"
echo ""
echo "📚 Useful commands:"
echo "   - View logs: kubectl logs -f deployment/iam-service"
echo "   - Describe pod: kubectl describe pod <pod-name>"
echo "   - Delete all: kubectl delete namespace iam-local"
