#!/usr/bin/env php
<?php
/**
 * CARE API - TESTE DE INTEGRAÇÃO E API ENDPOINTS
 * 
 * Este script testa especificamente os endpoints da API
 * e funcionalidades de integração do Care API.
 * 
 * @package Care_API\Tests
 */

define('CARE_API_TEST_MODE', true);

echo "🏥 CARE API - TESTE DE INTEGRAÇÃO E ENDPOINTS\n";
echo "==============================================\n\n";

/**
 * Classe para testes de integração do Care API
 */
class CareAPIIntegrationTester {
    
    private $results = [];
    private $total_tests = 0;
    private $passed_tests = 0;
    private $failed_tests = 0;
    
    public function __construct() {
        echo "🔧 Configurando ambiente de teste de integração...\n";
        $this->setup_mock_wp_environment();
        echo "✅ Ambiente configurado\n\n";
    }
    
    /**
     * Setup completo do ambiente WordPress mock
     */
    private function setup_mock_wp_environment() {
        // Definir constantes WordPress essenciais
        if (!defined('WP_DEBUG')) define('WP_DEBUG', true);
        if (!defined('ABSPATH')) define('ABSPATH', __DIR__ . '/');
        if (!defined('WP_CONTENT_DIR')) define('WP_CONTENT_DIR', __DIR__ . '/wp-content');
        if (!defined('WP_PLUGIN_DIR')) define('WP_PLUGIN_DIR', WP_CONTENT_DIR . '/plugins');
        
        // Mock global $wpdb
        global $wpdb;
        $wpdb = new stdClass();
        $wpdb->prefix = 'wp_';
        $wpdb->posts = 'wp_posts';
        $wpdb->users = 'wp_users';
        
        // Mock REST API classes
        if (!class_exists('WP_REST_Server')) {
            $this->create_rest_api_mocks();
        }
        
        // Mock WordPress core functions
        $this->mock_wordpress_functions();
    }
    
    /**
     * Criar mocks das classes REST API
     */
    private function create_rest_api_mocks() {
        if (!class_exists('WP_REST_Server')) {
            eval('
            class WP_REST_Server {
                const READABLE = "GET";
                const CREATABLE = "POST"; 
                const EDITABLE = "PUT";
                const DELETABLE = "DELETE";
                
                public function register_route($namespace, $route, $args) {
                    return true;
                }
            }
            ');
        }
        
        if (!class_exists('WP_REST_Response')) {
            eval('
            class WP_REST_Response {
                private $data;
                private $status = 200;
                
                public function __construct($data = null, $status = 200) {
                    $this->data = $data;
                    $this->status = $status;
                }
                
                public function get_data() { return $this->data; }
                public function get_status() { return $this->status; }
                public function set_status($status) { $this->status = $status; }
            }
            ');
        }
        
        if (!class_exists('WP_REST_Request')) {
            eval('
            class WP_REST_Request {
                private $method;
                private $route;
                private $params = [];
                
                public function __construct($method = "GET", $route = "") {
                    $this->method = $method;
                    $this->route = $route;
                }
                
                public function get_method() { return $this->method; }
                public function get_route() { return $this->route; }
                public function get_params() { return $this->params; }
                public function set_param($key, $value) { $this->params[$key] = $value; }
            }
            ');
        }
    }
    
    /**
     * Mock das principais funções WordPress
     */
    private function mock_wordpress_functions() {
        $functions = [
            'rest_ensure_response' => function($data) { return new WP_REST_Response($data); },
            'rest_url' => function($path) { return 'https://example.com/wp-json' . $path; },
            'get_rest_url' => function($blog_id, $path) { return 'https://example.com/wp-json' . $path; },
            'current_user_can' => function($capability) { return true; }, // Mock sempre autorizado para testes
            'wp_get_current_user' => function() { 
                return (object) ['ID' => 1, 'user_login' => 'test_user', 'user_email' => 'test@example.com']; 
            },
            'get_current_user_id' => function() { return 1; },
            'sanitize_text_field' => function($str) { return trim(strip_tags($str)); },
            'sanitize_email' => function($email) { return filter_var($email, FILTER_SANITIZE_EMAIL); },
            'wp_unslash' => function($value) { return stripslashes_deep($value); },
            'wp_create_nonce' => function($action) { return 'mock_nonce_12345'; },
            'wp_verify_nonce' => function($nonce, $action) { return true; },
            'current_time' => function($type) { return date($type); },
            'mysql2date' => function($format, $date) { return date($format, strtotime($date)); },
            'is_wp_error' => function($thing) { return $thing instanceof WP_Error; },
            'add_action' => function($tag, $function, $priority = 10) { return true; },
            'add_filter' => function($tag, $function, $priority = 10) { return true; },
            'do_action' => function($tag) { return true; },
            'apply_filters' => function($tag, $value) { return $value; },
        ];
        
        foreach ($functions as $name => $callback) {
            if (!function_exists($name)) {
                eval("function $name() { \$callback = " . var_export($callback, true) . "; return call_user_func_array(\$callback, func_get_args()); }");
            }
        }
        
        // Mock WP_Error class
        if (!class_exists('WP_Error')) {
            eval('class WP_Error { 
                private $errors = [];
                public function __construct($code = "", $message = "", $data = "") {
                    if (!empty($code)) $this->errors[$code] = [$message];
                }
                public function get_error_code() { return key($this->errors); }
                public function get_error_message() { return current(current($this->errors)); }
            }');
        }
    }
    
    /**
     * Executar todos os testes de integração
     */
    public function run_integration_tests() {
        echo "🚀 INICIANDO TESTES DE INTEGRAÇÃO\n";
        echo "==================================\n\n";
        
        // 1. TESTES DE ENDPOINTS ESTRUTURAIS
        $this->test_endpoint_files_structure();
        
        // 2. TESTES DE ROTAS REST API
        $this->test_rest_api_routes();
        
        // 3. TESTES DE AUTENTICAÇÃO
        $this->test_authentication_system();
        
        // 4. TESTES DE PERMISSÕES
        $this->test_permission_system();
        
        // 5. TESTES DE VALIDAÇÃO DE DADOS
        $this->test_data_validation();
        
        // 6. TESTES DE RESPOSTA PADRONIZADA
        $this->test_response_format();
        
        // 7. TESTES DE CACHE
        $this->test_cache_functionality();
        
        // 8. TESTES DE PERFORMANCE
        $this->test_performance_monitoring();
        
        // Relatório final
        $this->generate_integration_report();
    }
    
    /**
     * Testar estrutura dos arquivos de endpoints
     */
    private function test_endpoint_files_structure() {
        echo "🌐 1. TESTES DE ESTRUTURA DOS ENDPOINTS\n";
        echo "=======================================\n";
        
        $endpoints = [
            'class-clinic-endpoints.php' => 'Endpoint Clinicas',
            'class-patient-endpoints.php' => 'Endpoint Pacientes', 
            'class-doctor-endpoints.php' => 'Endpoint Médicos',
            'class-appointment-endpoints.php' => 'Endpoint Consultas',
            'class-encounter-endpoints.php' => 'Endpoint Encontros',
            'class-prescription-endpoints.php' => 'Endpoint Prescrições',
            'class-bill-endpoints.php' => 'Endpoint Faturas',
        ];
        
        foreach ($endpoints as $file => $description) {
            $this->run_test("$description - arquivo existe", function() use ($file) {
                return file_exists(__DIR__ . "/src/includes/endpoints/$file");
            });
            
            if (file_exists(__DIR__ . "/src/includes/endpoints/$file")) {
                $content = file_get_contents(__DIR__ . "/src/includes/endpoints/$file");
                
                $this->run_test("$description - classe definida", function() use ($content, $file) {
                    $class_name = str_replace(['class-', '-endpoints.php'], ['', ''], $file);
                    $class_name = str_replace('-', '_', $class_name);
                    return strpos($content, "class") !== false;
                });
                
                $this->run_test("$description - método register_routes", function() use ($content) {
                    return strpos($content, 'register_routes') !== false;
                });
                
                $this->run_test("$description - endpoints REST", function() use ($content) {
                    return strpos($content, 'register_rest_route') !== false || 
                           strpos($content, 'WP_REST_') !== false;
                });
            }
        }
        
        echo "\n";
    }
    
    /**
     * Testar estrutura das rotas REST API
     */
    private function test_rest_api_routes() {
        echo "🛣️  2. TESTES DE ROTAS REST API\n";
        echo "===============================\n";
        
        // Testes das rotas esperadas
        $expected_routes = [
            '/kivicare/v1/clinics' => 'Rota clinicas',
            '/kivicare/v1/patients' => 'Rota pacientes',
            '/kivicare/v1/doctors' => 'Rota médicos', 
            '/kivicare/v1/appointments' => 'Rota consultas',
            '/kivicare/v1/encounters' => 'Rota encontros',
            '/kivicare/v1/prescriptions' => 'Rota prescrições',
            '/kivicare/v1/bills' => 'Rota faturas',
        ];
        
        foreach ($expected_routes as $route => $description) {
            $this->run_test("$description existe", function() use ($route) {
                // Mock test - em ambiente real verificaria com get_rest_route
                // Por agora verificamos se a estrutura de endpoint existe
                $endpoint_file = str_replace(['/kivicare/v1/', 's'], ['', ''], $route);
                if ($endpoint_file === 'clinic') $endpoint_file = 'clinics';
                return file_exists(__DIR__ . "/src/includes/endpoints/class-{$endpoint_file}-endpoints.php");
            });
        }
        
        // Testar métodos HTTP esperados
        $methods = ['GET', 'POST', 'PUT', 'DELETE'];
        foreach ($methods as $method) {
            $this->run_test("Suporte método $method", function() use ($method) {
                // Verificar se pelo menos um endpoint suporta este método
                $endpoint_files = glob(__DIR__ . '/src/includes/endpoints/class-*-endpoints.php');
                foreach ($endpoint_files as $file) {
                    $content = file_get_contents($file);
                    if (strpos($content, "'methods' => '{$method}'") !== false ||
                        strpos($content, "methods.*{$method}") !== false ||
                        strpos($content, "WP_REST_Server::" . strtoupper($method)) !== false) {
                        return true;
                    }
                }
                return false;
            });
        }
        
        echo "\n";
    }
    
    /**
     * Testar sistema de autenticação
     */
    private function test_authentication_system() {
        echo "🔐 3. TESTES DE AUTENTICAÇÃO\n";
        echo "=============================\n";
        
        // Testar se JWT service existe
        $this->run_test('JWT Service existe', function() {
            return file_exists(__DIR__ . '/src/includes/services/class-jwt-service.php');
        });
        
        // Testar se Auth service existe  
        $this->run_test('Auth Service existe', function() {
            return file_exists(__DIR__ . '/src/includes/services/class-auth-service.php');
        });
        
        // Testar middleware JWT
        $this->run_test('JWT Middleware existe', function() {
            return file_exists(__DIR__ . '/src/includes/middleware/class-jwt-middleware.php');
        });
        
        // Testar estrutura JWT
        if (file_exists(__DIR__ . '/src/includes/services/class-jwt-service.php')) {
            $content = file_get_contents(__DIR__ . '/src/includes/services/class-jwt-service.php');
            
            $this->run_test('JWT - método generate_token', function() use ($content) {
                return strpos($content, 'generate_token') !== false;
            });
            
            $this->run_test('JWT - método validate_token', function() use ($content) {
                return strpos($content, 'validate_token') !== false;
            });
            
            $this->run_test('JWT - método refresh_token', function() use ($content) {
                return strpos($content, 'refresh_token') !== false;
            });
        }
        
        echo "\n";
    }
    
    /**
     * Testar sistema de permissões
     */
    private function test_permission_system() {
        echo "👮 4. TESTES DE PERMISSÕES\n";
        echo "===========================\n";
        
        $this->run_test('Permission Service existe', function() {
            return file_exists(__DIR__ . '/src/includes/services/class-permission-service.php');
        });
        
        // Testar capabilities definidas no plugin principal
        if (file_exists(__DIR__ . '/src/care-api.php')) {
            $content = file_get_contents(__DIR__ . '/src/care-api.php');
            
            $expected_caps = [
                'manage_care_api',
                'care_api_full_access',
                'care_api_medical_access', 
                'care_api_patient_access',
                'care_api_reception_access'
            ];
            
            foreach ($expected_caps as $cap) {
                $this->run_test("Capability '$cap' definida", function() use ($content, $cap) {
                    return strpos($content, $cap) !== false;
                });
            }
        }
        
        echo "\n";
    }
    
    /**
     * Testar validação de dados
     */
    private function test_data_validation() {
        echo "✅ 5. TESTES DE VALIDAÇÃO DE DADOS\n";
        echo "==================================\n";
        
        $this->run_test('Input Validator existe', function() {
            return file_exists(__DIR__ . '/src/includes/utils/class-input-validator.php');
        });
        
        if (file_exists(__DIR__ . '/src/includes/utils/class-input-validator.php')) {
            $content = file_get_contents(__DIR__ . '/src/includes/utils/class-input-validator.php');
            
            $validation_methods = [
                'validate_email',
                'validate_phone',
                'validate_required',
                'sanitize_input'
            ];
            
            foreach ($validation_methods as $method) {
                $this->run_test("Método $method existe", function() use ($content, $method) {
                    return strpos($content, $method) !== false;
                });
            }
        }
        
        echo "\n";
    }
    
    /**
     * Testar formato de resposta padronizado
     */
    private function test_response_format() {
        echo "📋 6. TESTES DE FORMATO DE RESPOSTA\n";
        echo "===================================\n";
        
        $this->run_test('Response Standardization Service existe', function() {
            return file_exists(__DIR__ . '/src/includes/services/class-response-standardization-service.php');
        });
        
        if (file_exists(__DIR__ . '/src/includes/services/class-response-standardization-service.php')) {
            $content = file_get_contents(__DIR__ . '/src/includes/services/class-response-standardization-service.php');
            
            $response_methods = [
                'success_response',
                'error_response', 
                'paginated_response',
                'standardize_response'
            ];
            
            foreach ($response_methods as $method) {
                $this->run_test("Método $method existe", function() use ($content, $method) {
                    return strpos($content, $method) !== false;
                });
            }
        }
        
        echo "\n";
    }
    
    /**
     * Testar funcionalidade de cache
     */
    private function test_cache_functionality() {
        echo "⚡ 7. TESTES DE CACHE\n";
        echo "=====================\n";
        
        $this->run_test('Cache Service existe', function() {
            return file_exists(__DIR__ . '/src/includes/services/class-cache-service.php');
        });
        
        if (file_exists(__DIR__ . '/src/includes/services/class-cache-service.php')) {
            $content = file_get_contents(__DIR__ . '/src/includes/services/class-cache-service.php');
            
            $cache_methods = [
                'get_cache',
                'set_cache',
                'delete_cache',
                'flush_cache'
            ];
            
            foreach ($cache_methods as $method) {
                $this->run_test("Cache método $method existe", function() use ($content, $method) {
                    return strpos($content, $method) !== false;
                });
            }
        }
        
        echo "\n";
    }
    
    /**
     * Testar monitoramento de performance
     */
    private function test_performance_monitoring() {
        echo "📊 8. TESTES DE PERFORMANCE\n";
        echo "============================\n";
        
        $this->run_test('Performance Monitoring Service existe', function() {
            return file_exists(__DIR__ . '/src/includes/services/class-performance-monitoring-service.php');
        });
        
        if (file_exists(__DIR__ . '/src/includes/services/class-performance-monitoring-service.php')) {
            $content = file_get_contents(__DIR__ . '/src/includes/services/class-performance-monitoring-service.php');
            
            $performance_methods = [
                'start_timer',
                'end_timer',
                'log_performance',
                'get_metrics'
            ];
            
            foreach ($performance_methods as $method) {
                $this->run_test("Performance método $method existe", function() use ($content, $method) {
                    return strpos($content, $method) !== false;
                });
            }
        }
        
        echo "\n";
    }
    
    /**
     * Executar um teste individual
     */
    private function run_test($name, $callback) {
        $this->total_tests++;
        
        try {
            $result = $callback();
            if ($result) {
                echo "✅ $name\n";
                $this->passed_tests++;
                $this->results[] = ['name' => $name, 'status' => 'PASS'];
            } else {
                echo "❌ $name\n";
                $this->failed_tests++;
                $this->results[] = ['name' => $name, 'status' => 'FAIL'];
            }
        } catch (Exception $e) {
            echo "💥 $name - ERROR: " . $e->getMessage() . "\n";
            $this->failed_tests++;
            $this->results[] = ['name' => $name, 'status' => 'ERROR', 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Gerar relatório de integração
     */
    private function generate_integration_report() {
        echo "\n🎯 RELATÓRIO DE INTEGRAÇÃO\n";
        echo "==========================\n\n";
        
        echo "📊 ESTATÍSTICAS GERAIS:\n";
        echo "  Total de testes: {$this->total_tests}\n";
        echo "  Testes aprovados: {$this->passed_tests}\n";
        echo "  Testes reprovados: {$this->failed_tests}\n";
        
        $success_rate = round(($this->passed_tests / $this->total_tests) * 100, 2);
        echo "  Taxa de sucesso: {$success_rate}%\n\n";
        
        // Análise por categoria
        $categories = [
            'Estrutura dos Endpoints' => 0,
            'Rotas REST API' => 0,
            'Autenticação' => 0,
            'Permissões' => 0,
            'Validação de Dados' => 0,
            'Formato de Resposta' => 0,
            'Cache' => 0,
            'Performance' => 0
        ];
        
        if ($success_rate >= 95) {
            echo "🏆 EXCELENTE! API está pronta para produção.\n";
        } elseif ($success_rate >= 80) {
            echo "👍 BOM! API tem boa estrutura, algumas melhorias necessárias.\n";
        } elseif ($success_rate >= 60) {
            echo "⚠️  REGULAR! API precisa de melhorias significativas.\n";
        } else {
            echo "🚨 CRÍTICO! API não está pronta, refatoração necessária.\n";
        }
        
        echo "\n🔧 RECOMENDAÇÕES ESPECÍFICAS:\n";
        
        $failed_by_category = [];
        foreach ($this->results as $result) {
            if ($result['status'] !== 'PASS') {
                $name = $result['name'];
                if (strpos($name, 'Endpoint') !== false) {
                    $failed_by_category['Endpoints'][] = $name;
                } elseif (strpos($name, 'JWT') !== false || strpos($name, 'Auth') !== false) {
                    $failed_by_category['Autenticação'][] = $name;
                } elseif (strpos($name, 'Permission') !== false || strpos($name, 'Capability') !== false) {
                    $failed_by_category['Permissões'][] = $name;
                } elseif (strpos($name, 'Cache') !== false) {
                    $failed_by_category['Cache'][] = $name;
                } else {
                    $failed_by_category['Outros'][] = $name;
                }
            }
        }
        
        if (empty($failed_by_category)) {
            echo "  ✨ Nenhuma recomendação específica - tudo funcionando!\n";
        } else {
            foreach ($failed_by_category as $category => $failures) {
                echo "  🔸 $category: " . count($failures) . " problemas\n";
            }
        }
        
        echo "\n📋 PRÓXIMAS AÇÕES PRIORITÁRIAS:\n";
        echo "  1. ✅ Corrigir problemas de sintaxe PHP nos modelos\n";
        echo "  2. 🔧 Implementar endpoints de autenticação\n"; 
        echo "  3. 🧪 Executar testes PHPUnit quando ambiente configurado\n";
        echo "  4. 🌍 Testar em ambiente WordPress real\n";
        echo "  5. 📱 Executar testes de API com Postman/Insomnia\n";
        
        echo "\n📅 Teste de integração executado em: " . date('Y-m-d H:i:s') . "\n";
        echo "🏥 Care API Integration Test Suite - Descomplicar®\n";
    }
}

// Executar testes de integração
$integration_tester = new CareAPIIntegrationTester();
$integration_tester->run_integration_tests();