#!/bin/bash

APP_NAME="codimd"

echo "=== [ $APP_NAME 資源狀態 ] ==="

# 1. 檢查 Pods
echo "--- Pods ---"
kubectl get pods -l "app in (codimd, codimd-db)" -o wide

echo ""

# 2. 檢查 Services
echo "--- Services ---"
kubectl get svc -l "app in (codimd, codimd-db)"

echo ""

# 3. 檢查 PVC (儲存)
echo "--- Storage (PVC) ---"
kubectl get pvc | grep codimd

echo ""

# 4. 檢查存取入口 (Ingress)
echo "--- Access Points (Ingress) ---"
kubectl get ingress -l "app=codimd" 2>/dev/null || kubectl get ingress | grep codimd

echo ""

# 5. 檢查資料庫連通性 (如果 Pod 在 Running)
DB_POD=$(kubectl get pod -l app=codimd-db -o jsonpath="{.items[0].metadata.name}" 2>/dev/null)
POD_STATUS=$(kubectl get pod $DB_POD -o jsonpath="{.status.phase}" 2>/dev/null)

if [ "$POD_STATUS" == "Running" ]; then
    echo "--- Database Connection Check ---"
    if kubectl exec $DB_POD -- psql -U codimd -d codimd -c "SELECT 1;" > /dev/null 2>&1; then
        echo "✅ Database is Ready and Accessible."
    else
        echo "❌ Database is Running but Connection Failed."
    fi
else
    echo "⏳ Waiting for Database Pod to be Ready..."
fi
