<?php
/**
 * Simple API Endpoints Structure Test
 *
 * @package Care_API
 * @version 1.0.0
 */

echo "🏥 CARE API - TESTE ESTRUTURAL DOS ENDPOINTS\n";
echo "============================================\n\n";

// Test 1: Check namespace consistency
echo "1. 🌐 VALIDANDO NAMESPACES\n";
echo "==========================\n";

$endpoint_files = [
    'class-auth-endpoints.php',
    'class-clinic-endpoints.php', 
    'class-patient-endpoints.php',
    'class-appointment-endpoints.php',
    'class-doctor-endpoints.php',
    'class-encounter-endpoints.php',
    'class-prescription-endpoints.php',
    'class-bill-endpoints.php'
];

$namespace_correct = 0;
foreach ($endpoint_files as $file) {
    $filepath = __DIR__ . '/src/includes/endpoints/' . $file;
    if (file_exists($filepath)) {
        $content = file_get_contents($filepath);
        
        if (strpos($content, "'kivicare/v1'") !== false) {
            echo "❌ $file - namespace incorreto (kivicare/v1)\n";
        } elseif (strpos($content, "'care/v1'") !== false || strpos($content, "self::NAMESPACE") !== false || strpos($content, "self::API_NAMESPACE") !== false) {
            echo "✅ $file - namespace correto\n";
            $namespace_correct++;
        } else {
            echo "⚠️ $file - namespace não detectado\n";
        }
    } else {
        echo "❌ $file - arquivo não encontrado\n";
    }
}

$namespace_percentage = round(($namespace_correct / count($endpoint_files)) * 100, 1);
echo "\n📊 Namespaces corretos: $namespace_correct/" . count($endpoint_files) . " ($namespace_percentage%)\n\n";

// Test 2: Check required methods
echo "2. 📋 VALIDANDO MÉTODOS DOS ENDPOINTS\n";
echo "=====================================\n";

$required_methods = [
    'class-auth-endpoints.php' => ['login', 'logout', 'refresh_token', 'validate_token'],
    'class-clinic-endpoints.php' => ['get_clinics', 'create_clinic', 'get_clinic', 'update_clinic'],
    'class-patient-endpoints.php' => ['get_patient', 'create_patient', 'update_patient'],
    'class-appointment-endpoints.php' => ['get_appointments', 'create_appointment', 'update_appointment'],
    'class-encounter-endpoints.php' => ['get_encounters', 'create_encounter', 'update_encounter'],
    'class-prescription-endpoints.php' => ['get_prescriptions', 'create_prescription', 'update_prescription'],
    'class-bill-endpoints.php' => ['get_bills', 'create_bill', 'update_bill'],
    'class-doctor-endpoints.php' => ['get_doctors', 'create_doctor', 'get_doctor', 'update_doctor']
];

$total_methods = 0;
$found_methods = 0;

foreach ($required_methods as $file => $methods) {
    echo "\n📁 $file:\n";
    $filepath = __DIR__ . '/src/includes/endpoints/' . $file;
    
    if (file_exists($filepath)) {
        $content = file_get_contents($filepath);
        
        foreach ($methods as $method) {
            $total_methods++;
            if (strpos($content, "function $method") !== false) {
                echo "  ✅ $method\n";
                $found_methods++;
            } else {
                echo "  ❌ $method\n";
            }
        }
    } else {
        foreach ($methods as $method) {
            $total_methods++;
            echo "  ❌ $method (arquivo não existe)\n";
        }
    }
}

$methods_percentage = round(($found_methods / $total_methods) * 100, 1);
echo "\n📊 Métodos encontrados: $found_methods/$total_methods ($methods_percentage%)\n\n";

// Test 3: Check register_routes method
echo "3. 🔧 VALIDANDO MÉTODO REGISTER_ROUTES\n";
echo "======================================\n";

$routes_found = 0;
foreach ($endpoint_files as $file) {
    $filepath = __DIR__ . '/src/includes/endpoints/' . $file;
    if (file_exists($filepath)) {
        $content = file_get_contents($filepath);
        
        if (strpos($content, 'register_routes') !== false) {
            echo "✅ $file - register_routes presente\n";
            $routes_found++;
        } else {
            echo "❌ $file - register_routes ausente\n";
        }
    }
}

$routes_percentage = round(($routes_found / count($endpoint_files)) * 100, 1);
echo "\n📊 Register routes: $routes_found/" . count($endpoint_files) . " ($routes_percentage%)\n\n";

// Test 4: Check WordPress REST API integration
echo "4. 🌍 VALIDANDO INTEGRAÇÃO REST API\n";
echo "===================================\n";

$rest_integration = 0;
foreach ($endpoint_files as $file) {
    $filepath = __DIR__ . '/src/includes/endpoints/' . $file;
    if (file_exists($filepath)) {
        $content = file_get_contents($filepath);
        
        if (strpos($content, 'register_rest_route') !== false) {
            echo "✅ $file - REST routes registradas\n";
            $rest_integration++;
        } else {
            echo "❌ $file - REST routes não encontradas\n";
        }
    }
}

$rest_percentage = round(($rest_integration / count($endpoint_files)) * 100, 1);
echo "\n📊 Integração REST API: $rest_integration/" . count($endpoint_files) . " ($rest_percentage%)\n\n";

// Test 5: Check security features
echo "5. 🔒 VALIDANDO RECURSOS DE SEGURANÇA\n";
echo "=====================================\n";

$security_features = ['permission_callback', 'sanitize_callback', 'validate_callback'];
$security_scores = [];

foreach ($endpoint_files as $file) {
    $filepath = __DIR__ . '/src/includes/endpoints/' . $file;
    if (file_exists($filepath)) {
        $content = file_get_contents($filepath);
        $file_security = 0;
        
        echo "\n📁 $file:\n";
        foreach ($security_features as $feature) {
            if (strpos($content, $feature) !== false) {
                echo "  ✅ $feature\n";
                $file_security++;
            } else {
                echo "  ❌ $feature\n";
            }
        }
        
        $security_scores[] = $file_security;
    }
}

$avg_security = round(array_sum($security_scores) / count($security_scores), 1);
$max_security = count($security_features);
$security_percentage = round(($avg_security / $max_security) * 100, 1);
echo "\n📊 Segurança média: $avg_security/$max_security ($security_percentage%)\n\n";

// Final Report
echo "🎯 RELATÓRIO FINAL\n";
echo "==================\n";

$scores = [
    'Namespaces' => $namespace_percentage,
    'Métodos' => $methods_percentage,
    'Register Routes' => $routes_percentage,
    'REST Integration' => $rest_percentage,
    'Segurança' => $security_percentage
];

$overall_score = array_sum($scores) / count($scores);

echo "\n📊 PONTUAÇÕES DETALHADAS:\n";
foreach ($scores as $category => $score) {
    $status = $score >= 80 ? "✅" : ($score >= 60 ? "⚠️" : "❌");
    echo "  $status $category: $score%\n";
}

echo "\n🏆 PONTUAÇÃO GERAL: " . round($overall_score, 1) . "%\n";

if ($overall_score >= 90) {
    echo "🏆 EXCELENTE! Endpoints prontos para produção\n";
    $status_emoji = "🏆";
} elseif ($overall_score >= 80) {
    echo "✅ MUITO BOM! Endpoints prontos para TDD GREEN phase\n";
    $status_emoji = "✅";
} elseif ($overall_score >= 70) {
    echo "👍 BOM! Pequenos ajustes necessários\n";  
    $status_emoji = "👍";
} elseif ($overall_score >= 60) {
    echo "⚠️ REGULAR! Melhorias necessárias\n";
    $status_emoji = "⚠️";
} else {
    echo "❌ RUIM! Refatoração necessária\n";
    $status_emoji = "❌";
}

echo "\n🚀 PRÓXIMAS AÇÕES:\n";
if ($overall_score >= 80) {
    echo "  1. ✅ Executar testes TDD CONTRACT\n";
    echo "  2. 🧪 Testar em ambiente WordPress\n";
    echo "  3. 📱 Validar com Postman/Insomnia\n";
    echo "  4. 📊 Monitorar performance\n";
} else {
    echo "  1. 🔧 Corrigir pontuações abaixo de 80%\n";
    echo "  2. 🛠️ Implementar métodos em falta\n";
    echo "  3. 🔒 Melhorar recursos de segurança\n";
    echo "  4. 🔄 Re-executar validação\n";
}

echo "\n📅 Teste executado em: " . date('Y-m-d H:i:s') . "\n";
echo "$status_emoji Care API Endpoints Structure Test - Descomplicar®\n";