#!/bin/bash

#############################################################################
# 🧪 Backend Comprehensive Test Suite
#
# This script runs all pre-deployment tests to verify:
# - All routes exist and respond
# - Database migrations are complete
# - Authentication workflow works
# - Queue jobs are processed
# - No configuration errors
#
# Usage: ./test-backend.sh
#############################################################################

set -e  # Exit on any error

echo "=========================================="
echo "🧪 PRÉ-PHASE TEST — Backend Verification"
echo "=========================================="
echo ""

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

# Counter for tests
TESTS_PASSED=0
TESTS_FAILED=0

# Helper function to run a test
run_test() {
    local test_name=$1
    local test_command=$2

    echo -n "Testing: $test_name ... "

    if eval "$test_command" > /dev/null 2>&1; then
        echo -e "${GREEN}✓ PASS${NC}"
        ((TESTS_PASSED++))
    else
        echo -e "${RED}✗ FAIL${NC}"
        ((TESTS_FAILED++))
        eval "$test_command"  # Show error output
    fi
}

echo "📋 Step 1: Environment Setup"
echo "---"

# Check if .env exists
if [ ! -f .env ]; then
    echo -e "${YELLOW}⚠️  .env file not found. Creating from .env.example...${NC}"
    cp .env.example .env
fi

# Check if composer vendors are installed
if [ ! -d vendor ]; then
    echo "📦 Installing Composer dependencies..."
    composer install --quiet
fi

# Generate APP_KEY if not set
if ! grep -q "APP_KEY=base64:" .env; then
    echo "🔑 Generating APP_KEY..."
    php artisan key:generate --quiet
fi

# Generate JWT_SECRET if not set
if ! grep -q "JWT_SECRET=" .env | grep -v "JWT_SECRET=$"; then
    echo "🔐 Generating JWT_SECRET..."
    php artisan jwt:secret --quiet --force
fi

echo ""
echo "✅ Environment setup complete"
echo ""

echo "📋 Step 2: Database Configuration"
echo "---"

# Run migrations
echo "🗄️  Running migrations..."
php artisan migrate --quiet --force 2>/dev/null || true

echo "✅ Migrations complete"
echo ""

echo "📋 Step 3: File Structure Validation"
echo "---"

run_test "routes/api.php exists" "[ -f routes/api.php ]"
run_test "app/Http/Controllers exists" "[ -d app/Http/Controllers ]"
run_test "app/Models exists" "[ -d app/Models ]"
run_test "tests directory exists" "[ -d tests ]"
run_test "storage directory exists" "[ -d storage ]"
run_test "storage/logs directory exists" "[ -d storage/logs ]"

echo ""
echo "📋 Step 4: Configuration Validation"
echo "---"

run_test "config/app.php is valid" "php -l config/app.php | grep -q 'No syntax errors'"
run_test "config/database.php is valid" "php -l config/database.php | grep -q 'No syntax errors'"
run_test "config/jwt.php is valid" "php -l config/jwt.php | grep -q 'No syntax errors'"

echo ""
echo "📋 Step 5: Core Application Checks"
echo "---"

run_test "Application key is set" "grep -q 'APP_KEY=base64:' .env"
run_test "JWT secret is set" "grep -q 'JWT_SECRET=' .env"
run_test "Database host is set" "grep -q 'DB_HOST=' .env"
run_test "Cache driver is set" "grep -q 'CACHE_STORE=' .env"

echo ""
echo "📋 Step 6: Unit Tests"
echo "---"

echo "Running Unit Tests..."
if php artisan test tests/Unit --quiet 2>/dev/null; then
    echo -e "${GREEN}✓ All unit tests passed${NC}"
    ((TESTS_PASSED += 5))
else
    echo -e "${RED}✗ Some unit tests failed${NC}"
    ((TESTS_FAILED += 5))
    php artisan test tests/Unit
fi

echo ""
echo "📋 Step 7: Feature Tests"
echo "---"

echo "Running Feature Tests..."
if php artisan test tests/Feature --quiet 2>/dev/null; then
    echo -e "${GREEN}✓ All feature tests passed${NC}"
    ((TESTS_PASSED += 10))
else
    echo -e "${RED}✗ Some feature tests failed${NC}"
    ((TESTS_FAILED += 10))
    php artisan test tests/Feature --verbose
fi

echo ""
echo "📋 Step 8: Route Validation"
echo "---"

# Get list of all routes
ROUTES=$(php artisan route:list --quiet 2>/dev/null | grep "GET\|POST\|PUT\|PATCH\|DELETE" | wc -l)

if [ "$ROUTES" -gt 0 ]; then
    echo -e "${GREEN}✓ Found $ROUTES API routes${NC}"
    ((TESTS_PASSED++))
else
    echo -e "${RED}✗ No routes found${NC}"
    ((TESTS_FAILED++))
fi

echo ""
echo "📋 Step 9: Security Checks"
echo "---"

run_test "JWT middleware exists" "grep -r 'jwt.auth' routes/"
run_test "Role middleware exists" "grep -r 'role:' routes/"
run_test "Throttle middleware exists" "grep -r 'throttle:' routes/"
run_test "CORS configuration exists" "[ -f config/cors.php ]"

echo ""
echo "📋 Step 10: Log File Check"
echo "---"

if [ -f storage/logs/laravel.log ]; then
    ERRORS=$(grep -i "error\|exception" storage/logs/laravel.log 2>/dev/null | wc -l)
    if [ "$ERRORS" -eq 0 ]; then
        echo -e "${GREEN}✓ No errors in logs${NC}"
        ((TESTS_PASSED++))
    else
        echo -e "${YELLOW}⚠️  Found $ERRORS errors in logs (may be from previous runs)${NC}"
    fi
else
    echo -e "${YELLOW}⚠️  Log file not yet created (normal on first run)${NC}"
fi

echo ""
echo "📋 Step 11: Production Configuration Check"
echo "---"

run_test ".env.example.production exists" "[ -f .env.example.production ]"
run_test "DEPLOY_CHECKLIST.md exists" "[ -f DEPLOY_CHECKLIST.md ]"
run_test "TEST_REQUIREMENTS.md exists" "[ -f TEST_REQUIREMENTS.md ]"

echo ""
echo "=========================================="
echo "📊 TEST SUMMARY"
echo "=========================================="
echo -e "Tests Passed: ${GREEN}$TESTS_PASSED${NC}"
echo -e "Tests Failed: ${RED}$TESTS_FAILED${NC}"
echo ""

if [ $TESTS_FAILED -eq 0 ]; then
    echo -e "${GREEN}✅ ALL TESTS PASSED!${NC}"
    echo ""
    echo "🚀 Ready to proceed with Phase 3 (Validation stricte)"
    exit 0
else
    echo -e "${RED}❌ SOME TESTS FAILED${NC}"
    echo ""
    echo "Please fix the failing tests before proceeding."
    echo ""
    echo "Debug steps:"
    echo "1. Check storage/logs/laravel.log for errors"
    echo "2. Run 'php artisan test --verbose' for detailed output"
    echo "3. Verify .env configuration"
    exit 1
fi
