#!/bin/bash

# Customer Portal V2 - Phase 1 Architecture Verification
# Final validation gate before Phase 2 can begin
#
# This script verifies:
# 1. No inline email normalization (strtolower(trim()) in Services
# 2. No inline email validation (filter_var) in Services
# 3. No raw string $email parameters in public methods (should use EmailAddress VO)
# 4. No references to old PhoneNumber utility
# 5. Old Utils/PhoneNumber.php deleted
# 6. No HTTP exceptions in Services (domain layer)
# 7. All service tests passing
#
# Exit code 0 = pass, 1 = fail
#
# @see V2-1.7: Architecture Verification (Grep Audit)

set -e

echo "Customer Portal V2 - Phase 1 Architecture Verification"
echo "=========================================================="
echo ""

FAILED=0
WARNINGS=0

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

# Function to report success
pass() {
    echo -e "${GREEN}PASS${NC}: $1"
}

# Function to report failure
fail() {
    echo -e "${RED}FAIL${NC}: $1"
    FAILED=1
}

# Function to report warning (non-blocking)
warn() {
    echo -e "${YELLOW}WARN${NC}: $1"
    WARNINGS=$((WARNINGS + 1))
}

# Function to report info
info() {
    echo -e "${BLUE}INFO${NC}: $1"
}

# Determine script directory and project root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Change to project root
cd "$PROJECT_ROOT"

echo "Project root: $PROJECT_ROOT"
echo ""

# ============================================================================
# 1. Check for inline email normalization
# ============================================================================
echo "1. Checking for inline email normalization..."
echo "----------------------------------------------"

INLINE_EMAIL=$(grep -r "strtolower(trim(" app/Domains/Customer/Services/ 2>/dev/null | wc -l | tr -d ' ')
if [ "$INLINE_EMAIL" -eq 0 ]; then
    pass "No inline email normalization in Services (0 instances)"
else
    fail "Found $INLINE_EMAIL instances of inline email normalization"
    echo "   These should be migrated to use EmailAddress::fromString()"
    echo ""
    grep -rn "strtolower(trim(" app/Domains/Customer/Services/ 2>/dev/null || true
    echo ""
fi

# ============================================================================
# 2. Check for inline email validation
# ============================================================================
echo ""
echo "2. Checking for inline email validation..."
echo "-------------------------------------------"

INLINE_VALIDATE=$(grep -r "filter_var.*FILTER_VALIDATE_EMAIL" app/Domains/Customer/Services/ 2>/dev/null | wc -l | tr -d ' ')
if [ "$INLINE_VALIDATE" -eq 0 ]; then
    pass "No inline email validation in Services (0 instances)"
else
    fail "Found $INLINE_VALIDATE instances of inline email validation"
    echo "   These should be migrated to use EmailAddress::fromString()"
    echo ""
    grep -rn "filter_var.*FILTER_VALIDATE_EMAIL" app/Domains/Customer/Services/ 2>/dev/null || true
    echo ""
fi

# ============================================================================
# 3. Check for raw string $email parameters in public methods
# ============================================================================
echo ""
echo "3. Checking for raw string email parameters..."
echo "-----------------------------------------------"

# Look for public methods with string $email parameter
# These should use EmailAddress type instead for type safety
RAW_EMAIL_PARAMS=$(grep -r "public.*function.*string \$email" app/Domains/Customer/Services/ 2>/dev/null | wc -l | tr -d ' ')
if [ "$RAW_EMAIL_PARAMS" -eq 0 ]; then
    pass "No raw string email parameters in public methods"
else
    # This is a warning, not a failure - some backward compat may be needed
    warn "Found $RAW_EMAIL_PARAMS public methods with raw string email parameters"
    echo "   Consider migrating to EmailAddress type for better type safety"
    echo ""
    grep -rn "public.*function.*string \$email" app/Domains/Customer/Services/ 2>/dev/null || true
    echo ""
fi

# ============================================================================
# 4. Check for old PhoneNumber utility usage
# ============================================================================
echo ""
echo "4. Checking for old PhoneNumber utility usage..."
echo "-------------------------------------------------"

OLD_PHONE=$(grep -r "App\\\\Utils\\\\PhoneNumber" app/ 2>/dev/null | wc -l | tr -d ' ')
if [ "$OLD_PHONE" -eq 0 ]; then
    pass "No usage of old PhoneNumber utility (0 instances)"
else
    fail "Found $OLD_PHONE references to old PhoneNumber utility"
    echo "   These should be migrated to App\\Domains\\Shared\\ValueObjects\\PhoneNumber"
    echo ""
    grep -rn "App\\\\Utils\\\\PhoneNumber" app/ 2>/dev/null || true
    echo ""
fi

# ============================================================================
# 5. Check if old Utils/PhoneNumber.php is deleted
# ============================================================================
echo ""
echo "5. Checking if old PhoneNumber utility deleted..."
echo "--------------------------------------------------"

if [ ! -f "app/Utils/PhoneNumber.php" ]; then
    pass "Old PhoneNumber utility deleted (app/Utils/PhoneNumber.php)"
else
    fail "Old PhoneNumber utility still exists: app/Utils/PhoneNumber.php"
    echo "   Delete this file after migrating all usages"
fi

# Also check if Utils directory is empty/deleted
if [ ! -d "app/Utils" ]; then
    pass "Old Utils directory deleted"
elif [ -z "$(ls -A app/Utils 2>/dev/null)" ]; then
    warn "Utils directory exists but is empty - consider deleting it"
else
    info "Utils directory contains other files (not related to Phase 1)"
    ls -la app/Utils/ 2>/dev/null || true
fi

# ============================================================================
# 6. Check for HTTP exceptions in Services
# ============================================================================
echo ""
echo "6. Checking for HTTP exceptions in Services..."
echo "-----------------------------------------------"

HTTP_EXCEPTIONS=$(grep -r "HttpException" app/Domains/Customer/Services/ 2>/dev/null | wc -l | tr -d ' ')
if [ "$HTTP_EXCEPTIONS" -eq 0 ]; then
    pass "No HTTP exceptions in Services (domain layer clean)"
else
    fail "Found $HTTP_EXCEPTIONS HTTP exceptions in Services"
    echo "   Services should throw domain exceptions, controllers catch and convert to HTTP"
    echo ""
    grep -rn "HttpException" app/Domains/Customer/Services/ 2>/dev/null || true
    echo ""
fi

# ============================================================================
# 7. Check for Value Object usage in Services
# ============================================================================
echo ""
echo "7. Checking for Value Object imports in Services..."
echo "----------------------------------------------------"

# Check that EmailAddress VO is used
EMAIL_VO_USAGE=$(grep -r "use App\\\\Domains\\\\Shared\\\\ValueObjects\\\\EmailAddress" app/Domains/Customer/Services/ 2>/dev/null | wc -l | tr -d ' ')
if [ "$EMAIL_VO_USAGE" -gt 0 ]; then
    pass "EmailAddress VO imported in $EMAIL_VO_USAGE service files"
else
    warn "EmailAddress VO not imported in any service files"
fi

# Check that PhoneNumber VO is used
PHONE_VO_USAGE=$(grep -r "use App\\\\Domains\\\\Shared\\\\ValueObjects\\\\PhoneNumber" app/Domains/Customer/Services/ 2>/dev/null | wc -l | tr -d ' ')
if [ "$PHONE_VO_USAGE" -gt 0 ]; then
    pass "PhoneNumber VO imported in $PHONE_VO_USAGE service files"
else
    warn "PhoneNumber VO not imported in any service files"
fi

# ============================================================================
# 8. Check for domain exception usage
# ============================================================================
echo ""
echo "8. Checking for domain exception usage..."
echo "------------------------------------------"

DOMAIN_EXCEPTIONS=$(grep -r "use App\\\\Domains\\\\Customer\\\\Exceptions" app/Domains/Customer/Services/ 2>/dev/null | wc -l | tr -d ' ')
if [ "$DOMAIN_EXCEPTIONS" -gt 0 ]; then
    pass "Domain exceptions imported in $DOMAIN_EXCEPTIONS service files"
else
    warn "Domain exceptions not imported in any service files"
fi

# Check for generic Exception throws (non-blocking)
GENERIC_EXCEPTIONS=$(grep -r "throw new \\\\Exception" app/Domains/Customer/Services/ 2>/dev/null | wc -l | tr -d ' ')
if [ "$GENERIC_EXCEPTIONS" -eq 0 ]; then
    pass "No generic Exception throws in Services"
else
    warn "Found $GENERIC_EXCEPTIONS generic Exception throws"
    echo "   Consider using domain-specific exceptions for better error handling"
    grep -rn "throw new \\\\Exception" app/Domains/Customer/Services/ 2>/dev/null || true
fi

# ============================================================================
# 9. Run Phase 1 service tests
# ============================================================================
echo ""
echo "9. Running Phase 1 service tests..."
echo "------------------------------------"

# Count expected tests
EXPECTED_TESTS=$(vendor/bin/phpunit tests/Unit/Domains/Customer/Services/ --list-tests 2>/dev/null | tail -n +3 | wc -l | tr -d ' ')
info "Found $EXPECTED_TESTS service tests to run"

# Run tests with stop-on-failure for faster feedback
if vendor/bin/phpunit tests/Unit/Domains/Customer/Services/ --stop-on-failure --colors=never 2>&1; then
    pass "All service tests passing"
else
    fail "Service tests failed"
    echo ""
    echo "Run manually for details:"
    echo "  vendor/bin/phpunit tests/Unit/Domains/Customer/Services/ --testdox"
fi

# ============================================================================
# Summary
# ============================================================================
echo ""
echo "=========================================================="

if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}Phase 1 Verification PASSED${NC}"
    echo ""
    if [ $WARNINGS -gt 0 ]; then
        echo -e "${YELLOW}$WARNINGS warnings detected (non-blocking)${NC}"
        echo "Review warnings above for potential improvements."
        echo ""
    fi
    echo "Verification Summary:"
    echo "  - No inline email normalization in Services"
    echo "  - No inline email validation in Services"
    echo "  - No old PhoneNumber utility usage"
    echo "  - Old PhoneNumber utility file deleted"
    echo "  - No HTTP exceptions in domain layer"
    echo "  - All service tests passing"
    echo ""
    echo "Ready to proceed to Phase 2"
    echo ""
    echo "Next steps:"
    echo "  1. Create git tag: git tag -a customer-portal-v2-phase1-complete -m 'Phase 1 complete'"
    echo "  2. Push tag: git push origin customer-portal-v2-phase1-complete"
    echo "  3. Start Phase 2 stories (DTOs and Repository Pattern)"
    exit 0
else
    echo -e "${RED}Phase 1 Verification FAILED${NC}"
    echo ""
    echo "Phase 1 is NOT complete. Fix issues above before proceeding to Phase 2."
    echo ""
    echo "Common fixes:"
    echo "  - Replace strtolower(trim(\$email)) with EmailAddress::fromString(\$email)->toString()"
    echo "  - Replace filter_var(\$email, FILTER_VALIDATE_EMAIL) with EmailAddress::fromString(\$email)"
    echo "  - Delete app/Utils/PhoneNumber.php after migrating to PhoneNumber VO"
    echo "  - Replace HttpException with domain exceptions"
    echo ""
    exit 1
fi
