#!/bin/bash
# Validation script for user and plan persistence
# Verifies: User save/load, Plan save/load, Offline persistence, Sync queue

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(dirname "$SCRIPT_DIR")"

echo ""
echo "╔══════════════════════════════════════════════════════════════════════════╗"
echo "║         🔍 PERSISTENCE VALIDATION - User & Plan Save/Load               ║"
echo "╚══════════════════════════════════════════════════════════════════════════╝"
echo ""

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

check_mark="${GREEN}✅${NC}"
cross_mark="${RED}❌${NC}"
warning_mark="${YELLOW}⚠️${NC}"
info_mark="${BLUE}ℹ️${NC}"

# Track results
total_checks=0
passed_checks=0
failed_checks=0

check() {
  local name=$1
  local command=$2
  local expected=$3
  
  total_checks=$((total_checks + 1))
  
  echo -n "  Checking: $name ... "
  
  if eval "$command" | grep -q "$expected"; then
    echo -e "${check_mark}"
    passed_checks=$((passed_checks + 1))
    return 0
  else
    echo -e "${cross_mark}"
    failed_checks=$((failed_checks + 1))
    return 1
  fi
}

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  1️⃣  USER PERSISTENCE (Auth0 → Firestore)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

echo "  📝 Backend User Endpoints:"
check "POST /api/auth/sync" \
  "grep -r 'syncUser' $ROOT_DIR/apps/api/src/modules/auth/" \
  "syncUser"

check "GET /api/auth/profile" \
  "grep -r 'getUserProfile' $ROOT_DIR/apps/api/src/modules/auth/" \
  "getUserProfile"

echo ""
echo "  💾 Firestore User Operations:"
check "syncAuth0User() saves to Firestore" \
  "grep -r 'collection.*users.*doc.*uid.*set' $ROOT_DIR/apps/api/src/modules/auth/auth.service.ts" \
  "collection('users')"

check "getUserProfile() loads from Firestore" \
  "grep -r 'collection.*users.*doc.*uid.*get' $ROOT_DIR/apps/api/src/modules/auth/auth.service.ts" \
  "get()"

echo ""
echo "  🎯 Frontend User Flow:"
check "authStore calls /api/auth/sync on login" \
  "grep -r '/api/auth/sync' $ROOT_DIR/apps/web/src/modules/auth/stores/authStore.ts" \
  "/api/auth/sync"

check "authStore calls /api/auth/profile" \
  "grep -r '/api/auth/profile' $ROOT_DIR/apps/web/src/modules/auth/stores/authStore.ts" \
  "/api/auth/profile"

check "User stored in Auth0 localStorage cache" \
  "grep -r 'cacheLocation.*localstorage' $ROOT_DIR/apps/web/src/modules/auth/stores/authStore.ts" \
  "localstorage"

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  2️⃣  PLAN PERSISTENCE (Frontend → API → Firestore)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

echo "  📝 Backend Plan Endpoints:"
check "POST /api/planner/plans" \
  "grep -r 'createPlan' $ROOT_DIR/apps/api/src/modules/planner/planner.routes.ts" \
  "createPlan"

check "PATCH /api/planner/plans/:id" \
  "grep -r 'updatePlan' $ROOT_DIR/apps/api/src/modules/planner/planner.routes.ts" \
  "updatePlan"

check "GET /api/planner/plans" \
  "grep -r 'getPlans' $ROOT_DIR/apps/api/src/modules/planner/planner.routes.ts" \
  "getPlans"

echo ""
echo "  💾 Firestore Plan Operations:"
check "createPlan() saves to Firestore" \
  "grep -A 20 'async createPlan' $ROOT_DIR/apps/api/src/modules/planner/planner.repository.ts" \
  "add(planData)"

check "updatePlan() updates Firestore" \
  "grep -A 10 'async updatePlan' $ROOT_DIR/apps/api/src/modules/planner/planner.repository.ts" \
  "docRef.update"

check "findPlanById() loads from Firestore" \
  "grep -A 10 'async findPlanById' $ROOT_DIR/apps/api/src/modules/planner/planner.repository.ts" \
  ".get()"

echo ""
echo "  🎯 Frontend Plan Flow:"
check "plannerService.createPlan() calls API" \
  "grep -r 'request.*POST.*data.*dto' $ROOT_DIR/apps/web/src/modules/planner/services/plannerService.ts" \
  "POST"

check "plannerService.updatePlan() calls API" \
  "grep -r 'request.*PATCH.*data.*updates' $ROOT_DIR/apps/web/src/modules/planner/services/plannerService.ts" \
  "PATCH"

check "plannerStore.loadPlans() loads from API" \
  "grep -r 'plannerService.getPlans' $ROOT_DIR/apps/web/src/modules/planner/stores/plannerStore.ts" \
  "getPlans"

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  3️⃣  OFFLINE PERSISTENCE (IndexedDB + Sync Queue)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

echo "  💾 IndexedDB Plan Cache:"
check "IndexedDB schema defined (Dexie)" \
  "grep -r 'class PlannerDB extends Dexie' $ROOT_DIR/apps/web/src/modules/offline/services/indexedDBService.ts" \
  "PlannerDB"

check "savePlan() caches to IndexedDB" \
  "grep -r 'async savePlan.*Plan.*void' $ROOT_DIR/apps/web/src/modules/offline/services/indexedDBService.ts" \
  "savePlan"

check "getPlan() reads from IndexedDB" \
  "grep -r 'async getPlan.*string.*Plan' $ROOT_DIR/apps/web/src/modules/offline/services/indexedDBService.ts" \
  "getPlan"

check "plannerService saves to IndexedDB after API" \
  "grep -r 'indexedDBService.savePlan' $ROOT_DIR/apps/web/src/modules/planner/services/plannerService.ts" \
  "savePlan"

echo ""
echo "  🔄 Sync Queue (Offline Actions):"
check "SyncQueue queues actions when offline" \
  "grep 'async queueAction' $ROOT_DIR/apps/web/src/modules/offline/services/indexedDBService.ts" \
  "queueAction"

check "SyncQueue processes with exponential backoff" \
  "grep -r 'calculateBackoff.*retries' $ROOT_DIR/apps/web/src/modules/offline/services/syncQueueService.ts" \
  "calculateBackoff"

check "SyncQueue auto-processes every 30s" \
  "grep -r 'startAutoProcess.*30000' $ROOT_DIR/apps/web/src/modules/planner/services/plannerService.ts" \
  "30000"

check "plannerService queues offline creates" \
  "grep -r 'syncQueue.queueCreatePlan' $ROOT_DIR/apps/web/src/modules/planner/services/plannerService.ts" \
  "queueCreatePlan"

check "plannerService queues offline updates" \
  "grep -r 'syncQueue.queueUpdatePlan' $ROOT_DIR/apps/web/src/modules/planner/services/plannerService.ts" \
  "queueUpdatePlan"

echo ""
echo "  🌐 Offline Detection:"
check "plannerService checks navigator.onLine" \
  "grep -r 'navigator.onLine' $ROOT_DIR/apps/web/src/modules/planner/services/plannerService.ts" \
  "onLine"

check "Optimistic UI updates when offline" \
  "grep -A 3 'OFFLINE' $ROOT_DIR/apps/web/src/modules/planner/services/plannerService.ts" \
  "tempPlan"

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  4️⃣  DATA FLOW VERIFICATION"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

echo "  🔄 Complete User Flow:"
echo "      1. Auth0 login → JWT token"
echo "      2. authStore.initialize() → POST /api/auth/sync"
echo "      3. auth.service.syncAuth0User() → Firestore users/{uid}.set()"
echo "      4. authStore loads profile → GET /api/auth/profile"
echo "      5. auth.service.getUserProfile() → Firestore users/{uid}.get()"
echo "      6. User cached in Auth0 localStorage"
echo ""

echo "  🔄 Complete Plan Flow (Online):"
echo "      1. User clicks 'Create Plan' → plannerStore.createPlan()"
echo "      2. plannerService.createPlan() → POST /api/planner/plans"
echo "      3. planner.repository.createPlan() → Firestore plans/{id}.add()"
echo "      4. plannerService saves to IndexedDB → indexedDBService.savePlan()"
echo "      5. plannerStore updates state → plans.value.push()"
echo ""

echo "  🔄 Complete Plan Flow (Offline):"
echo "      1. User clicks 'Create Plan' (offline) → plannerStore.createPlan()"
echo "      2. plannerService.createPlan() catches OFFLINE error"
echo "      3. Creates temp plan → indexedDBService.savePlan(tempPlan)"
echo "      4. Queues action → syncQueue.queueCreatePlan()"
echo "      5. Auto-process after 30s → retry with exponential backoff"
echo "      6. On success → removes from queue + updates Firestore"
echo ""

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "  📊 VALIDATION SUMMARY"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo -e "  Total checks: $total_checks"
echo -e "  ${check_mark} Passed: $passed_checks"
echo -e "  ${cross_mark} Failed: $failed_checks"
echo ""

if [ $failed_checks -eq 0 ]; then
  echo -e "${check_mark} ${GREEN}ALL PERSISTENCE CHECKS PASSED!${NC}"
  echo ""
  echo "✅ Users are saved to Firestore and loaded correctly"
  echo "✅ Plans are saved to Firestore and cached in IndexedDB"
  echo "✅ Offline actions are queued and synced on reconnection"
  echo "✅ Data persistence is fully implemented"
  echo ""
  exit 0
else
  echo -e "${cross_mark} ${RED}SOME PERSISTENCE CHECKS FAILED${NC}"
  echo ""
  echo "⚠️  Review the failed checks above"
  echo "⚠️  Check implementation in corresponding files"
  echo ""
  exit 1
fi
