<?php
namespace Gestoreasy\Core;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Gestoreasy\Core\Routing\Router;
use Gestoreasy\Core\Module\ModuleManager;
use Gestoreasy\Core\Tenant\TenantContext;
use Gestoreasy\Core\Tenant\TenantAdmin;
use Gestoreasy\Core\Http\RateLimitMiddleware;

class Kernel {
    private Router $router;
    private ModuleManager $modules;

    public function __construct() {
        $this->router = new Router();
        $this->modules = new ModuleManager($this->router);
        $this->registerBaseRoutes();
        $this->modules->loadModules(__DIR__ . '/../../modules');
    }

    private function registerBaseRoutes(): void {
        $this->router->get('/health', function (Request $r) {
            $versionFile = __DIR__ . '/../../VERSION';
            $version = is_file($versionFile) ? trim(file_get_contents($versionFile)) : '0.1.0';
            return Response::json(['status' => 'ok', 'version' => $version]);
        });
        // Debug: listar módulos detectados (temporário)
        $this->router->get('/debug/modules', function (Request $r) {
            $dir = __DIR__ . '/../../modules';
            $files = glob($dir . '/*/Module.php') ?: [];
            return Response::json(['dir' => $dir, 'is_dir' => is_dir($dir), 'count' => count($files), 'files' => $files]);
        });
        // Debug: listar rotas registradas (temporário)
        $this->router->get('/debug/routes', function (Request $r) {
            return Response::json($this->router->list());
        });
        // Debug: status de carregamento de módulos
        $this->router->get('/debug/modules-status', function (Request $r) {
            return Response::json($this->modules->debugLoaded());
        });
    }

    public function handle(Request $req): Response {
        TenantContext::bootstrapFromRequest($req);
        // Executar migrações pendentes automaticamente para o tenant atual
        try { TenantAdmin::runMigrations(TenantContext::getTenantId()); } catch (\Throwable $e) { /* tolerar falhas menores */ }
        // Recriar a conexão do tenant para evitar cursores ativos remanescentes das migrações
        try { \Gestoreasy\Core\Tenant\ConnectionManager::refreshTenantConnection(TenantContext::getTenantId()); } catch (\Throwable $e) {}
        $rateRes = RateLimitMiddleware::enforceForSensitiveRoutes($req);
        if ($rateRes instanceof Response) {
            return $rateRes;
        }
        return $this->router->dispatch($req);
    }
}
