<?php
namespace Modules\Wms;

use Gestoreasy\Core\Module\ModuleInterface;
use Gestoreasy\Core\Routing\Router;
use Gestoreasy\Core\Auth\AuthMiddleware;
use Gestoreasy\Core\Auth\Rbac;
use Modules\Wms\Controllers\WarehouseController;
use Modules\Wms\Controllers\BinMovementsController;
use Modules\Wms\Controllers\InventoryController;
use Modules\Wms\Controllers\WmsViewsController;
use Modules\Wms\Controllers\MobileController;
use Modules\Wms\Controllers\MobileApiController;
use Modules\Wms\Controllers\AnalyticsController;
use Modules\Wms\Controllers\PickingController;

class Module implements ModuleInterface {
    public function register(Router $router): void {
        $wh = new WarehouseController();
        $bm = new BinMovementsController();
        $inv = new InventoryController();
        $views = new WmsViewsController();
        $analytics = new AnalyticsController();
        $picking = new PickingController();

        // Views (HTML)
        $router->get('/wms/warehouses', [$views, 'viewWarehouses'], [AuthMiddleware::requireAuthHtml(), Rbac::requirePermissions(['wms.read'])]);
        $router->get('/wms/bins', [$views, 'viewBins'], [AuthMiddleware::requireAuthHtml(), Rbac::requirePermissions(['wms.read'])]);
        $router->get('/wms/movimentos', [$views, 'viewMovements'], [AuthMiddleware::requireAuthHtml(), Rbac::requirePermissions(['wms.read'])]);
        // Nova view: Analytics BI
        $router->get('/wms/analytics', [$views, 'viewAnalytics'], [AuthMiddleware::requireAuthHtml(), Rbac::requirePermissions(['wms.read'])]);

        // Armazéns e endereços (bins)
        $router->get('/api/wms/warehouses', [$wh, 'listWarehouses'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);
        $router->get('/api/wms/warehouses/filters', [$wh, 'getWarehouseFilters'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);
        $router->post('/api/wms/warehouses', [$wh, 'createWarehouse'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.create'])]);
        $router->put('/api/wms/warehouses/{id}', [$wh, 'updateWarehouse'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.update'])]);
        $router->delete('/api/wms/warehouses/{id}', [$wh, 'deleteWarehouse'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.delete'])]);

        $router->get('/api/wms/bins', [$wh, 'listBins'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);
        $router->post('/api/wms/bins', [$wh, 'createBin'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.create'])]);
        $router->put('/api/wms/bins/{id}', [$wh, 'updateBin'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.update'])]);
        $router->delete('/api/wms/bins/{id}', [$wh, 'deleteBin'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.delete'])]);

        // Tracking em tempo real (polling)
        $router->get('/api/wms/tracking/events', [$wh, 'listTrackingEvents'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);
        $router->post('/api/wms/tracking/events', [$wh, 'createTrackingEvent'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.update'])]);

        // Movimentação entre endereços
        $router->get('/api/wms/movements', [$bm, 'list'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);
        $router->get('/api/wms/movements/export.csv', [$bm, 'exportCsv'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);
        $router->post('/api/wms/movements/transfer', [$bm, 'transfer'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.update'])]);
        $router->get('/api/wms/bins/levels', [$bm, 'levelsByBin'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);

        // Inventário e Configurações
        $router->get('/api/wms/inventory', [$inv, 'listSessions'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);
        $router->post('/api/wms/inventory/start', [$inv, 'startSession'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.update'])]);
        $router->get('/api/wms/inventory/entries', [$inv, 'listEntries'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);
        $router->get('/api/wms/inventory/entries/export.csv', [$inv, 'exportCsvEntries'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);
        $router->get('/api/wms/settings', [$inv, 'getSettings'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);
        $router->put('/api/wms/settings', [$inv, 'saveSettings'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.update'])]);

        // Coletor Mobile: ingestão, validação, confirmação e fila
        // Ingest e confirm aceitam X-API-Key de dispositivo (validado no controller) ou JWT; não exigimos middleware aqui para permitir integração com coletor.
        $router->post('/api/wms/mobile/inventory/ingest', [MobileController::class, 'ingest'], []);
        $router->post('/api/wms/mobile/inventory/validate', [MobileController::class, 'validate'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);
        $router->post('/api/wms/mobile/inventory/confirm', [MobileController::class, 'confirm'], []);
        $router->get('/api/wms/mobile/inventory/queue/pending', [MobileController::class, 'listPending'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);
        $router->post('/api/wms/mobile/inventory/queue/process', [MobileController::class, 'processPending'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.update'])]);

        // Endpoints genéricos para PWA do coletor móvel
        // Sem middleware de auth: usam chave de dispositivo via header/query
        $router->get('/ping', [MobileApiController::class, 'ping']);
        $router->post('/events', [MobileApiController::class, 'events']);
        // Aliases sob /mobile para compatibilidade com PWA configurado com base "/mobile"
        $router->get('/mobile/ping', [MobileApiController::class, 'ping']);
        $router->post('/mobile/events', [MobileApiController::class, 'events']);

        // Listagem de recebimento/expedição (visualização interna)
        $router->get('/api/wms/mobile/receiving', [MobileApiController::class, 'listReceiving'], [AuthMiddleware::requireAuthHtml(), Rbac::requirePermissions(['wms.read'])]);
        $router->get('/api/wms/mobile/shipping', [MobileApiController::class, 'listShipping'], [AuthMiddleware::requireAuthHtml(), Rbac::requirePermissions(['wms.read'])]);

        // BI e Alertas
        $router->get('/api/wms/bi/overview', [$analytics, 'overview'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);
        $router->get('/api/wms/bi/alerts', [$analytics, 'alerts'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);

        // Exportações CSV de recebimento/expedição (raw)
        $router->get('/api/wms/mobile/receiving/export.csv', [$analytics, 'exportReceivingCsv'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);
        $router->get('/api/wms/mobile/shipping/export.csv', [$analytics, 'exportShippingCsv'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);

        // Picking/Separação de Pedidos
        $router->get('/api/wms/picking/pedidos-pendentes', [$picking, 'listPedidosPendentes'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);
        $router->post('/api/wms/picking/gerar-lista/{order_id}', [$picking, 'gerarListaPicking'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.update'])]);
        $router->get('/api/wms/picking/lista/{picking_list_id}/itens', [$picking, 'listItensPicking'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.read'])]);
        $router->post('/api/wms/picking/confirmar-separacao/{item_id}', [$picking, 'confirmarSeparacao'], [AuthMiddleware::requireAuth(), Rbac::requirePermissions(['wms.update'])]);

        // Picking Mobile (Coletor) - endpoints sem autenticação JWT obrigatória (usam API key)
        $router->get('/api/wms/mobile/picking/pedidos', [MobileController::class, 'listPickingPedidos'], []);
        $router->get('/api/wms/mobile/picking/lista/{picking_list_id}/itens', [MobileController::class, 'getPickingItens'], []);
        $router->post('/api/wms/mobile/picking/confirmar/{item_id}', [MobileController::class, 'confirmarPickingMobile'], []);
    }
    public function name(): string { return 'Wms'; }
    public function version(): string { return '0.1.0'; }
    public function dependencies(): array { return ['Estoque', 'Produtos']; }
}