#!/bin/bash

# Backend Quality Audit Script
# Checks: TypeScript errors, type duplicates, unused exports, module completeness

set -e

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

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Backend Quality Audit${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Change to repo root
cd "$(dirname "$0")/.."

TOTAL_ERRORS=0

# ===================================
# 1. TypeScript Errors
# ===================================
echo -e "${YELLOW}[1/8] TypeScript Compilation Check...${NC}"
if pnpm --filter @my-roadtrip/api type-check 2>&1 | grep -q "error TS"; then
  ERROR_COUNT=$(pnpm --filter @my-roadtrip/api type-check 2>&1 | grep "error TS" | wc -l | xargs)
  echo -e "${RED}   ✗ Found $ERROR_COUNT TypeScript errors${NC}"
  pnpm --filter @my-roadtrip/api type-check 2>&1 | grep "error TS" | head -10
  TOTAL_ERRORS=$((TOTAL_ERRORS + ERROR_COUNT))
else
  echo -e "${GREEN}   ✓ No TypeScript errors${NC}"
fi
echo ""

# ===================================
# 2. Type Duplicates
# ===================================
echo -e "${YELLOW}[2/8] Checking for duplicate type definitions...${NC}"
DUPLICATE_TYPES=$(grep -r "^export interface\|^export type" packages/types/src/*.ts | \
  awk -F: '{print $2}' | \
  sed 's/export interface //g' | \
  sed 's/export type //g' | \
  awk '{print $1}' | \
  sort | uniq -d)

if [ -n "$DUPLICATE_TYPES" ]; then
  echo -e "${RED}   ✗ Found duplicate types:${NC}"
  echo "$DUPLICATE_TYPES"
  TOTAL_ERRORS=$((TOTAL_ERRORS + $(echo "$DUPLICATE_TYPES" | wc -l)))
else
  echo -e "${GREEN}   ✓ No duplicate types${NC}"
fi
echo ""

# ===================================
# 3. Missing Exports
# ===================================
echo -e "${YELLOW}[3/8] Checking for missing type exports...${NC}"
MISSING_EXPORTS=0

# Check each domain file is exported in index.ts
for file in packages/types/src/*.types.ts; do
  basename=$(basename "$file" .ts)
  if ! grep -q "from './$basename'" packages/types/src/index.ts; then
    echo -e "${RED}   ✗ Missing export: $basename${NC}"
    MISSING_EXPORTS=$((MISSING_EXPORTS + 1))
  fi
done

if [ $MISSING_EXPORTS -eq 0 ]; then
  echo -e "${GREEN}   ✓ All type files exported${NC}"
else
  TOTAL_ERRORS=$((TOTAL_ERRORS + MISSING_EXPORTS))
fi
echo ""

# ===================================
# 4. Module Registration
# ===================================
echo -e "${YELLOW}[4/8] Checking module registration...${NC}"
MISSING_MODULES=0

# Check if all modules in apps/api/src/modules/ are registered in core/modules.ts
for module_dir in apps/api/src/modules/*; do
  if [ -d "$module_dir" ]; then
    module_name=$(basename "$module_dir")
    
    # Skip test directories
    if [[ "$module_name" == "__tests__" ]]; then
      continue
    fi
    
    # Check if module is registered
    if ! grep -q "$module_name" apps/api/src/core/modules.ts; then
      echo -e "${RED}   ✗ Module not registered: $module_name${NC}"
      MISSING_MODULES=$((MISSING_MODULES + 1))
    fi
  fi
done

if [ $MISSING_MODULES -eq 0 ]; then
  echo -e "${GREEN}   ✓ All modules registered${NC}"
else
  TOTAL_ERRORS=$((TOTAL_ERRORS + MISSING_MODULES))
fi
echo ""

# ===================================
# 5. Unused Imports (ESLint)
# ===================================
echo -e "${YELLOW}[5/8] Checking for unused imports...${NC}"
UNUSED_COUNT=$(pnpm --filter @my-roadtrip/api lint 2>&1 | grep -c "is defined but never used" || true)

if [ $UNUSED_COUNT -gt 0 ]; then
  echo -e "${RED}   ✗ Found $UNUSED_COUNT unused imports${NC}"
  TOTAL_ERRORS=$((TOTAL_ERRORS + UNUSED_COUNT))
else
  echo -e "${GREEN}   ✓ No unused imports${NC}"
fi
echo ""

# ===================================
# 6. Route Coverage
# ===================================
echo -e "${YELLOW}[6/8] Checking route registration...${NC}"
UNREGISTERED_ROUTES=0

# Find all .routes.ts files
for route_file in apps/api/src/modules/**/*.routes.ts; do
  if [ -f "$route_file" ]; then
    module_name=$(basename "$(dirname "$route_file")")
    route_function=$(grep -o "export.*function [a-zA-Z]*Routes" "$route_file" | awk '{print $3}' || echo "")
    
    if [ -n "$route_function" ]; then
      # Check if route is called in modules.ts or module.ts
      if ! grep -rq "$route_function" apps/api/src/core/modules.ts apps/api/src/modules/$module_name/*.module.ts 2>/dev/null; then
        echo -e "${RED}   ✗ Route not registered: $route_function ($module_name)${NC}"
        UNREGISTERED_ROUTES=$((UNREGISTERED_ROUTES + 1))
      fi
    fi
  fi
done

if [ $UNREGISTERED_ROUTES -eq 0 ]; then
  echo -e "${GREEN}   ✓ All routes registered${NC}"
else
  TOTAL_ERRORS=$((TOTAL_ERRORS + UNREGISTERED_ROUTES))
fi
echo ""

# ===================================
# 7. Firestore Index Check
# ===================================
echo -e "${YELLOW}[7/8] Checking Firestore indexes...${NC}"

# Check if firebase/firestore.indexes.json exists
if [ ! -f "firebase/firestore.indexes.json" ]; then
  echo -e "${RED}   ✗ Missing firestore.indexes.json${NC}"
  TOTAL_ERRORS=$((TOTAL_ERRORS + 1))
else
  INDEX_COUNT=$(jq '.indexes | length' firebase/firestore.indexes.json)
  echo -e "${GREEN}   ✓ Found $INDEX_COUNT Firestore indexes${NC}"
fi
echo ""

# ===================================
# 8. Security Rules Check
# ===================================
echo -e "${YELLOW}[8/8] Checking Firestore security rules...${NC}"

if [ ! -f "firebase/firestore.rules" ]; then
  echo -e "${RED}   ✗ Missing firestore.rules${NC}"
  TOTAL_ERRORS=$((TOTAL_ERRORS + 1))
else
  RULE_COUNT=$(grep -c "match /" firebase/firestore.rules || echo 0)
  echo -e "${GREEN}   ✓ Found $RULE_COUNT Firestore rules${NC}"
fi
echo ""

# ===================================
# Summary
# ===================================
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Audit Summary${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

if [ $TOTAL_ERRORS -eq 0 ]; then
  echo -e "${GREEN}✓ Backend audit passed!${NC}"
  echo -e "${GREEN}  All checks completed successfully.${NC}"
  exit 0
else
  echo -e "${RED}✗ Backend audit failed!${NC}"
  echo -e "${RED}  Total issues found: $TOTAL_ERRORS${NC}"
  echo ""
  echo -e "${YELLOW}Recommendations:${NC}"
  echo "  1. Fix TypeScript errors: pnpm type-check"
  echo "  2. Remove duplicate types in packages/types/"
  echo "  3. Update packages/types/src/index.ts with missing exports"
  echo "  4. Register missing modules in apps/api/src/core/modules.ts"
  echo "  5. Clean up unused imports: pnpm lint --fix"
  echo "  6. Register missing routes in module files"
  echo "  7. Add Firestore indexes for compound queries"
  echo "  8. Define Firestore security rules"
  exit 1
fi
