#!/bin/bash

# Cleanup Kubernetes resources
# Usage: ./cleanup.sh [environment] [--force]

set -e

ENVIRONMENT=${1:-prod}
FORCE=${2}
NAMESPACE="portfolio-${ENVIRONMENT}"

echo "🧹 Cleaning up resources in ${ENVIRONMENT} environment..."

if [[ "${FORCE}" != "--force" ]]; then
    echo "⚠️  This will delete all resources in namespace ${NAMESPACE}"
    echo "   Use --force flag to skip this confirmation"
    read -p "Are you sure? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "❌ Cleanup cancelled"
        exit 1
    fi
fi

echo "🗑️  Deleting resources..."

# Delete in reverse order of dependencies
kubectl delete -f ../monitoring/ --ignore-not-found=true
kubectl delete -f ../hpa/ --ignore-not-found=true
kubectl delete -f ../ingress/ --ignore-not-found=true
kubectl delete -f ../services/ --ignore-not-found=true
kubectl delete -f ../deployments/services/ --ignore-not-found=true
kubectl delete -f ../deployments/infrastructure/ --ignore-not-found=true

# Delete PVCs (this will delete data!)
echo "⚠️  Deleting persistent volumes (this will delete data!)"
kubectl delete pvc --all -n ${NAMESPACE} --ignore-not-found=true

# Delete ConfigMaps and Secrets
kubectl delete configmap --all -n ${NAMESPACE} --ignore-not-found=true
kubectl delete secret --all -n ${NAMESPACE} --ignore-not-found=true

# Optionally delete namespace
read -p "Delete namespace ${NAMESPACE}? (y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    kubectl delete namespace ${NAMESPACE} --ignore-not-found=true
    echo "✅ Namespace ${NAMESPACE} deleted"
else
    echo "ℹ️  Namespace ${NAMESPACE} preserved"
fi

echo "✅ Cleanup completed!"