#!/bin/bash

# Customer Portal V2 - Phase 0 Architecture Validation
# Verifies all Phase 0 patterns are correctly implemented
# Exit code 0 = pass, 1 = fail

set -e

echo "Customer Portal V2 - Phase 0 Architecture Validation"
echo "========================================================"
echo ""

FAILED=0

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
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
warn() {
    echo -e "${YELLOW}WARN${NC}: $1"
}

echo "1. Checking Value Objects..."
echo "----------------------------"

# EmailAddress VO
if [ -f "app/Domains/Shared/ValueObjects/EmailAddress.php" ]; then
    pass "EmailAddress.php exists"

    # Check class structure
    if grep -q "final readonly class EmailAddress" app/Domains/Shared/ValueObjects/EmailAddress.php; then
        pass "EmailAddress is final readonly"
    else
        fail "EmailAddress must be 'final readonly class'"
    fi

    if grep -q "private function __construct" app/Domains/Shared/ValueObjects/EmailAddress.php; then
        pass "EmailAddress has private constructor"
    else
        fail "EmailAddress must have private constructor"
    fi

    # Check required methods
    for method in "fromString" "toString" "equals" "domain" "localPart"; do
        if grep -q "public.*function $method" app/Domains/Shared/ValueObjects/EmailAddress.php; then
            pass "EmailAddress has $method() method"
        else
            fail "EmailAddress missing $method() method"
        fi
    done
else
    fail "EmailAddress.php does not exist"
fi

# PhoneNumber VO
if [ -f "app/Domains/Shared/ValueObjects/PhoneNumber.php" ]; then
    pass "PhoneNumber.php exists"

    if grep -q "final readonly class PhoneNumber" app/Domains/Shared/ValueObjects/PhoneNumber.php; then
        pass "PhoneNumber is final readonly"
    else
        fail "PhoneNumber must be 'final readonly class'"
    fi

    if grep -q "private function __construct" app/Domains/Shared/ValueObjects/PhoneNumber.php; then
        pass "PhoneNumber has private constructor"
    else
        fail "PhoneNumber must have private constructor"
    fi
else
    fail "PhoneNumber.php does not exist"
fi

# VerificationCode VO
if [ -f "app/Domains/Shared/ValueObjects/VerificationCode.php" ]; then
    pass "VerificationCode.php exists"

    if grep -q "final readonly class VerificationCode" app/Domains/Shared/ValueObjects/VerificationCode.php; then
        pass "VerificationCode is final readonly"
    else
        fail "VerificationCode must be 'final readonly class'"
    fi

    if grep -q "private function __construct" app/Domains/Shared/ValueObjects/VerificationCode.php; then
        pass "VerificationCode has private constructor"
    else
        fail "VerificationCode must have private constructor"
    fi

    # Check security features
    if grep -q "hash_equals" app/Domains/Shared/ValueObjects/VerificationCode.php; then
        pass "VerificationCode uses timing-safe comparison (hash_equals)"
    else
        fail "VerificationCode must use hash_equals() for timing-safe comparison"
    fi

    if grep -q "random_int" app/Domains/Shared/ValueObjects/VerificationCode.php; then
        pass "VerificationCode uses cryptographic random (random_int)"
    else
        fail "VerificationCode must use random_int() for secure generation"
    fi
else
    fail "VerificationCode.php does not exist"
fi

echo ""
echo "2. Checking Domain Exceptions..."
echo "--------------------------------"

# Check all 7 exceptions exist
EXCEPTIONS=(
    "InvalidEmailAddressException"
    "InvalidPhoneNumberException"
    "InvalidVerificationCodeException"
    "EmailUnchangedException"
    "VerificationCodeExpiredException"
    "VerificationCodeMismatchException"
    "OrderOwnershipException"
)

for exception in "${EXCEPTIONS[@]}"; do
    if [ -f "app/Domains/Customer/Exceptions/${exception}.php" ]; then
        pass "${exception}.php exists"

        if grep -q "final class ${exception}" app/Domains/Customer/Exceptions/${exception}.php; then
            pass "${exception} is final"
        else
            fail "${exception} must be final class"
        fi
    else
        fail "${exception}.php does not exist"
    fi
done

echo ""
echo "3. Checking Tests..."
echo "--------------------"

# Check test files exist
if [ -f "tests/Unit/Domains/Shared/ValueObjects/EmailAddressTest.php" ]; then
    pass "EmailAddressTest.php exists"
else
    fail "EmailAddressTest.php does not exist"
fi

if [ -f "tests/Unit/Domains/Shared/ValueObjects/PhoneNumberTest.php" ]; then
    pass "PhoneNumberTest.php exists"
else
    fail "PhoneNumberTest.php does not exist"
fi

if [ -f "tests/Unit/Domains/Shared/ValueObjects/VerificationCodeTest.php" ]; then
    pass "VerificationCodeTest.php exists"
else
    fail "VerificationCodeTest.php does not exist"
fi

if [ -f "tests/Unit/Domains/Customer/Exceptions/DomainExceptionsTest.php" ]; then
    pass "DomainExceptionsTest.php exists"
else
    fail "DomainExceptionsTest.php does not exist"
fi

echo ""
echo "4. Running Tests..."
echo "-------------------"

# Run Phase 0 tests
echo "Running EmailAddressTest..."
if vendor/bin/phpunit tests/Unit/Domains/Shared/ValueObjects/EmailAddressTest.php --stop-on-failure 2>/dev/null; then
    pass "EmailAddressTest passed"
else
    fail "EmailAddressTest failed"
fi

echo "Running PhoneNumberTest..."
if vendor/bin/phpunit tests/Unit/Domains/Shared/ValueObjects/PhoneNumberTest.php --stop-on-failure 2>/dev/null; then
    pass "PhoneNumberTest passed"
else
    fail "PhoneNumberTest failed"
fi

echo "Running VerificationCodeTest..."
if vendor/bin/phpunit tests/Unit/Domains/Shared/ValueObjects/VerificationCodeTest.php --stop-on-failure 2>/dev/null; then
    pass "VerificationCodeTest passed"
else
    fail "VerificationCodeTest failed"
fi

echo "Running DomainExceptionsTest..."
if vendor/bin/phpunit tests/Unit/Domains/Customer/Exceptions/DomainExceptionsTest.php --stop-on-failure 2>/dev/null; then
    pass "DomainExceptionsTest passed"
else
    fail "DomainExceptionsTest failed"
fi

echo ""
echo "5. Checking for Anti-Patterns (Phase 1 Migration Targets)..."
echo "-------------------------------------------------------------"
echo "Note: These checks identify code that should be migrated in Phase 1."
echo "Phase 0 creates the foundation (VOs, exceptions); Phase 1 migrates services."
echo ""

# Check for inline email normalization (will be migrated in Phase 1)
INLINE_EMAIL=$(grep -r "strtolower(trim(" app/Domains/Customer/Services/ 2>/dev/null | wc -l || echo "0")
INLINE_EMAIL=$(echo "$INLINE_EMAIL" | tr -d ' ')
if [ "$INLINE_EMAIL" -eq 0 ]; then
    pass "No inline email normalization in Services"
else
    warn "Found $INLINE_EMAIL instances of inline email normalization (Phase 1 migration target)"
fi

# Check for inline email validation (will be migrated in Phase 1)
INLINE_VALIDATE=$(grep -r "filter_var.*FILTER_VALIDATE_EMAIL" app/Domains/Customer/Services/ 2>/dev/null | wc -l || echo "0")
INLINE_VALIDATE=$(echo "$INLINE_VALIDATE" | tr -d ' ')
if [ "$INLINE_VALIDATE" -eq 0 ]; then
    pass "No inline email validation in Services"
else
    warn "Found $INLINE_VALIDATE instances of inline email validation (Phase 1 migration target)"
fi

# Check for HTTP exceptions in Services (will be migrated in Phase 1)
HTTP_EXCEPTIONS=$(grep -r "HttpException" app/Domains/Customer/Services/ 2>/dev/null | wc -l || echo "0")
HTTP_EXCEPTIONS=$(echo "$HTTP_EXCEPTIONS" | tr -d ' ')
if [ "$HTTP_EXCEPTIONS" -eq 0 ]; then
    pass "No HTTP exceptions in Services"
else
    warn "Found $HTTP_EXCEPTIONS instances of HTTP exceptions (Phase 1 migration target)"
fi

# Check for generic Exception throws in Services
GENERIC_EXCEPTIONS=$(grep -r "throw new \\\\Exception" app/Domains/Customer/Services/ 2>/dev/null | wc -l || echo "0")
GENERIC_EXCEPTIONS=$(echo "$GENERIC_EXCEPTIONS" | tr -d ' ')
if [ "$GENERIC_EXCEPTIONS" -eq 0 ]; then
    pass "No generic exceptions in Services"
else
    warn "Found $GENERIC_EXCEPTIONS instances of generic Exception throws (Phase 1 migration target)"
fi

echo ""
echo "========================================================"

if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}Phase 0 Validation PASSED${NC}"
    echo ""
    echo "All Value Objects implemented correctly"
    echo "All Domain Exceptions created"
    echo "All tests passing"
    echo "No architectural anti-patterns detected"
    echo ""
    echo "Ready to proceed to Phase 1"
    echo ""
    echo "Next steps:"
    echo "1. Manual code review (optional but recommended)"
    echo "2. Create git tag: git tag -a customer-portal-v2-phase0-complete -m 'Phase 0 complete'"
    echo "3. Start Phase 1 stories"
    exit 0
else
    echo -e "${RED}Phase 0 Validation FAILED${NC}"
    echo ""
    echo "Phase 0 is NOT complete. Fix issues above before proceeding to Phase 1."
    echo ""
    exit 1
fi
