<?php
namespace Modules\SettingsUI;

use Gestoreasy\Core\Module\ModuleInterface;
use Gestoreasy\Core\Routing\Router;
use Gestoreasy\Core\Auth\AuthMiddleware;
use Gestoreasy\Core\Auth\Rbac;
use Gestoreasy\Core\View\View;
use Modules\SettingsUI\Controllers\SettingsController;
use Modules\SettingsUI\Controllers\BackupController;
use Gestoreasy\Core\Auth\MfaService;
use Gestoreasy\Core\Http\Response;
use Gestoreasy\Core\Http\Request;

class Module implements ModuleInterface {
    public function register(Router $router): void {
        $api = new SettingsController();
        // Views (HTML) para Configurações
        $render = function(string $view, array $params = []){
            return View::renderWithLayout($view, $params);
        };

        // Sistema
        $router->get('/settings/params', function() use ($render){
            return $render('settings/params', ['title' => 'Parâmetros do Sistema']);
        }, [AuthMiddleware::requireAuthHtml(), Rbac::requirePermissions(['settings.access'])]);

        $router->get('/settings/rbac', function() use ($render){
            return $render('settings/rbac', ['title' => 'Permissões (RBAC)']);
        }, [AuthMiddleware::requireAuthHtml(), Rbac::requirePermissions(['settings.access'])]);

        // Empresa
        $router->get('/settings/company', function() use ($render){
            return $render('settings/company', ['title' => 'Dados da Empresa']);
        }, [AuthMiddleware::requireAuthHtml(), Rbac::requirePermissions(['settings.access'])]);

        // Backup
        $backupCtrl = new BackupController();
        $router->get('/settings/backup', function() use ($render){
            return $render('settings/backup', ['title' => 'Backup do Sistema']);
        }, [AuthMiddleware::requireAuthHtml(), Rbac::requirePermissions(['settings.access'])]);
        
        $router->get('/api/settings/backup/info', [$backupCtrl, 'getBackupInfo'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['settings.access'])]);
        $router->get('/api/settings/backup/json', [$backupCtrl, 'generateJsonBackup'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['settings.access'])]);
        $router->get('/api/settings/backup/csv', [$backupCtrl, 'generateCsvBackup'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['settings.access'])]);

        // Removido: gerenciamento duplicado de usuários em /settings/users (usar Cadastros → Usuários)

        // API: Parâmetros do Sistema
        $router->get('/api/settings', [$api, 'get'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['settings.access'])]);
        $router->put('/api/settings', [$api, 'put'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['settings.access'])]);

        // Requer MFA
        $requireMfa = function (Request $r) {
            $user = \Gestoreasy\Core\Auth\UserContext::get($r);
            $uid = (int)($user['sub'] ?? 0);
            $tok = (string)$r->header('x-mfa-token');
            if ($uid <= 0 || $tok === '') return Response::json(['error' => 'MFA requerido'], 403);
            if (!MfaService::validateToken($tok, $uid)) return Response::json(['error' => 'MFA inválido ou expirado'], 403);
            return true;
        };
        // API: Dados da Empresa (perfil do tenant)
        $router->get('/api/settings/company', function (Request $r) use ($api, $requireMfa) {
            $mfa = $requireMfa($r); if ($mfa instanceof Response) return $mfa;
            return $api->getCompany($r);
        }, [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['settings.access'])]);
        $router->put('/api/settings/company', function (Request $r) use ($api, $requireMfa) {
            $mfa = $requireMfa($r); if ($mfa instanceof Response) return $mfa;
            return $api->putCompany($r);
        }, [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['settings.access'])]);
        $router->post('/api/settings/company/cert-upload', function (Request $r) use ($api, $requireMfa) {
            $mfa = $requireMfa($r); if ($mfa instanceof Response) return $mfa;
            return $api->uploadCompanyCert($r);
        }, [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['settings.access'])]);
    }
    public function name(): string { return 'SettingsUI'; }
    public function version(): string { return '0.1.0'; }
    public function dependencies(): array { return []; }
}