#!/bin/bash

# Configuration
NAMESPACE="haumdaucher"
REGISTRY="registry.haumdaucher.de"
IMAGE_BASE_NAME="haumdaucher-website"
IMAGE_NAME="$REGISTRY/$IMAGE_BASE_NAME"
TAG="latest"

echo "🚀 Starting deployment for Haumdaucher..."

# Create namespace if it doesn't exist
kubectl create namespace $NAMESPACE --dry-run=client -o yaml | kubectl apply -f -

# Build the docker image
echo "📦 Building Docker image..."

# Try to fetch Firebase config from Terraform
if [ -d "terraform" ]; then
    echo "🔍 Detected Terraform directory. Fetching Firebase config..."
    cd terraform
    TF_OUT=$(terraform output -json firebase_config 2>/dev/null)
    cd ..
    
    if [ ! -z "$TF_OUT" ]; then
        echo "✅ Firebase config found."
        FIREBASE_ARGS=(
            --build-arg VITE_FIREBASE_API_KEY=$(echo $TF_OUT | jq -r .apiKey)
            --build-arg VITE_FIREBASE_AUTH_DOMAIN=$(echo $TF_OUT | jq -r .authDomain)
            --build-arg VITE_FIREBASE_PROJECT_ID=$(echo $TF_OUT | jq -r .projectId)
            --build-arg VITE_FIREBASE_STORAGE_BUCKET=$(echo $TF_OUT | jq -r .storageBucket)
            --build-arg VITE_FIREBASE_MESSAGING_SENDER_ID=$(echo $TF_OUT | jq -r .messagingSenderId)
            --build-arg VITE_FIREBASE_APP_ID=$(echo $TF_OUT | jq -r .appId)
        )
    else
        echo "⚠️ Terraform output 'firebase_config' not found. Ensure required env vars are set."
    fi
fi

docker build -t $IMAGE_NAME:$TAG "${FIREBASE_ARGS[@]}" .

# Push the docker image
echo "📤 Pushing Docker image to $REGISTRY..."
docker push $IMAGE_NAME:$TAG

# Apply manifests
echo "🎡 Applying Kubernetes manifests..."
kubectl apply -f k8s-manifests.yaml

# Force rollout restart to pick up the new 'latest' image
echo "🔄 Restarting deployment to pull latest image..."
kubectl rollout restart deployment/haumdaucher-website -n $NAMESPACE

echo "✅ Deployment complete!"
echo "Check status with: kubectl get pods -n $NAMESPACE"
