<?php
namespace Modules\Cadastros;

use Gestoreasy\Core\Module\ModuleInterface;
use Gestoreasy\Core\Routing\Router;
use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;
use Gestoreasy\Core\Auth\AuthMiddleware;
use Gestoreasy\Core\Auth\Rbac;
use Gestoreasy\Core\View\View;
use Modules\Cadastros\Controllers\CadastrosController;

class Module implements ModuleInterface {
    public function register(Router $router): void {
        $ctrl = new CadastrosController();
        // Middleware dinâmico de permissão por entidade
        $permFor = function(string $op){
            return function (Request $r) use ($op) {
                $params = $r->get('params', []);
                $entity = (string)($params[0] ?? '');
                if ($entity === '') {
                    return new Response(404, ['error' => ['message' => 'Entidade não informada']]);
                }
                $mw = Rbac::requirePermissions(["cadastros.$entity.$op"]);
                return $mw($r);
            };
        };

        // Views genéricas por entidade
        $router->get('/cadastros/{entity}', [$ctrl, 'viewEntity'], [AuthMiddleware::requireAuthHtml(), $permFor('read')]);

        // API CRUD genérico
        $router->get('/api/cadastros/{entity}', [$ctrl, 'list'], [AuthMiddleware::requireAuth(), $permFor('read')]);
        $router->get('/api/cadastros/{entity}/{id}', [$ctrl, 'getById'], [AuthMiddleware::requireAuth(), $permFor('read')]);
        $router->post('/api/cadastros/{entity}', [$ctrl, 'create'], [AuthMiddleware::requireAuth(), $permFor('create')]);
        $router->put('/api/cadastros/{entity}/{id}', [$ctrl, 'update'], [AuthMiddleware::requireAuth(), $permFor('update')]);
        $router->delete('/api/cadastros/{entity}/{id}', [$ctrl, 'delete'], [AuthMiddleware::requireAuth(), $permFor('delete')]);
    }
    public function name(): string { return 'Cadastros'; }
    public function version(): string { return '0.1.0'; }
    public function dependencies(): array { return []; }
}