<?php
declare(strict_types=1);

use App\Core\Application;
use App\Core\Http\Request;
use App\Core\Http\Response;
use App\Modules\Auth\AuthController;
use App\Modules\Auth\AuthMiddleware;
use App\Modules\Cron\CronHandlerFactory;
use App\Modules\Cron\CronRepository;
use App\Modules\Orders\OrdersController;
use App\Modules\Orders\OrderImportRepository;
use App\Modules\Orders\OrdersRepository;
use App\Modules\Settings\AllegroApiClient;
use App\Modules\Settings\AllegroDeliveryMappingController;
use App\Modules\Settings\AllegroIntegrationController;
use App\Modules\Settings\AllegroIntegrationRepository;
use App\Modules\Settings\AllegroOAuthClient;
use App\Modules\Settings\AllegroOrderImportService;
use App\Modules\Settings\AllegroStatusDiscoveryService;
use App\Modules\Settings\AllegroStatusMappingController;
use App\Modules\Settings\AllegroTokenManager;
use App\Modules\Settings\AllegroStatusMappingRepository;
use App\Modules\Settings\OrderStatusRepository;
use App\Modules\Settings\ApaczkaApiClient;
use App\Modules\Settings\ApaczkaIntegrationController;
use App\Modules\Settings\ApaczkaIntegrationRepository;
use App\Modules\Settings\CarrierDeliveryMethodMappingRepository;
use App\Modules\Settings\InpostIntegrationController;
use App\Modules\Settings\InpostIntegrationRepository;
use App\Modules\Settings\IntegrationsHubController;
use App\Modules\Settings\IntegrationsRepository;
use App\Modules\Settings\ShopproIntegrationsController;
use App\Modules\Settings\ShopproIntegrationsRepository;
use App\Modules\Settings\ShopproStatusMappingRepository;
use App\Modules\Settings\CompanySettingsController;
use App\Modules\Settings\CompanySettingsRepository;
use App\Modules\Settings\ReceiptConfigController;
use App\Modules\Settings\ReceiptConfigRepository;
use App\Modules\Settings\EmailMailboxController;
use App\Modules\Settings\EmailMailboxRepository;
use App\Modules\Settings\EmailTemplateController;
use App\Modules\Settings\EmailTemplateRepository;
use App\Modules\Settings\IntegrationSecretCipher;
use App\Modules\Email\AttachmentGenerator;
use App\Modules\Email\EmailSendingService;
use App\Modules\Email\VariableResolver;
use App\Modules\Accounting\AccountingController;
use App\Modules\Accounting\ReceiptController;
use App\Modules\Accounting\ReceiptRepository;
use App\Modules\Accounting\ReceiptService;
use App\Modules\Automation\AutomationController;
use App\Modules\Automation\AutomationRepository;
use App\Modules\Automation\AutomationService;
use App\Modules\Automation\AutomationExecutionLogRepository;
use App\Modules\Settings\CronSettingsController;
use App\Modules\Settings\DeliveryStatusMappingController;
use App\Modules\Settings\SettingsController;
use App\Modules\Shipments\ApaczkaShipmentService;
use App\Modules\Shipments\AllegroShipmentService;
use App\Modules\Shipments\InpostShipmentService;
use App\Modules\Shipments\ShipmentController;
use App\Modules\Shipments\ShipmentPackageRepository;
use App\Modules\Shipments\ShipmentPresetController;
use App\Modules\Shipments\DeliveryStatusMappingRepository;
use App\Modules\Shipments\ShipmentPresetRepository;
use App\Modules\Shipments\ShipmentProviderRegistry;
use App\Modules\Printing\ApiKeyMiddleware;
use App\Modules\Printing\PrintApiController;
use App\Modules\Printing\PrintApiKeyRepository;
use App\Modules\Printing\PrintJobRepository;
use App\Modules\Settings\PrintSettingsController;
use App\Modules\Users\UsersController;

return static function (Application $app): void {
    $router = $app->router();
    $template = $app->template();
    $auth = $app->auth();
    $translator = $app->translator();

    $authController = new AuthController($template, $auth, $translator);
    $usersController = new UsersController($template, $translator, $auth, $app->users());
    $shipmentPackageRepositoryForOrders = new ShipmentPackageRepository($app->db());
    $receiptConfigRepository = new ReceiptConfigRepository($app->db());
    $receiptRepository = new ReceiptRepository($app->db());
    $settingsController = new SettingsController($template, $translator, $auth, $app->migrator(), $app->orderStatuses());
    $allegroIntegrationRepository = new AllegroIntegrationRepository(
        $app->db(),
        (string) $app->config('app.integrations.secret', '')
    );
    $allegroStatusMappingRepository = new AllegroStatusMappingRepository($app->db());
    $carrierDeliveryMappings = new CarrierDeliveryMethodMappingRepository($app->db());
    $allegroOAuthClient = new AllegroOAuthClient();
    $allegroTokenManager = new AllegroTokenManager($allegroIntegrationRepository, $allegroOAuthClient);
    $apaczkaApiClient = new ApaczkaApiClient();
    $cronRepository = new CronRepository($app->db());
    $apaczkaIntegrationRepository = new ApaczkaIntegrationRepository(
        $app->db(),
        (string) $app->config('app.integrations.secret', '')
    );
    $allegroStatusDiscoveryService = new AllegroStatusDiscoveryService(
        $allegroTokenManager,
        new AllegroApiClient(),
        $allegroStatusMappingRepository
    );
    $allegroStatusMappingController = new AllegroStatusMappingController(
        $translator,
        $allegroStatusMappingRepository,
        $app->orderStatuses(),
        $allegroStatusDiscoveryService
    );
    $allegroDeliveryMappingController = new AllegroDeliveryMappingController(
        $translator,
        $allegroIntegrationRepository,
        $allegroOAuthClient,
        new AllegroApiClient(),
        $carrierDeliveryMappings,
        $apaczkaIntegrationRepository,
        $apaczkaApiClient
    );
    $allegroIntegrationController = new AllegroIntegrationController(
        $template,
        $translator,
        $auth,
        $allegroIntegrationRepository,
        $allegroStatusMappingRepository,
        $app->orderStatuses(),
        $cronRepository,
        $allegroOAuthClient,
        new AllegroOrderImportService(
            $allegroIntegrationRepository,
            $allegroTokenManager,
            new AllegroApiClient(),
            new OrderImportRepository($app->db()),
            $allegroStatusMappingRepository,
            new OrdersRepository($app->db())
        ),
        $allegroStatusDiscoveryService,
        (string) $app->config('app.url', ''),
        $allegroDeliveryMappingController
    );
    $apaczkaIntegrationController = new ApaczkaIntegrationController(
        $template,
        $translator,
        $auth,
        $apaczkaIntegrationRepository,
        $apaczkaApiClient
    );
    $inpostIntegrationRepository = new InpostIntegrationRepository(
        $app->db(),
        (string) $app->config('app.integrations.secret', '')
    );
    $inpostIntegrationController = new InpostIntegrationController(
        $template,
        $translator,
        $auth,
        $inpostIntegrationRepository
    );
    $shopproIntegrationsRepository = new ShopproIntegrationsRepository(
        $app->db(),
        (string) $app->config('app.integrations.secret', '')
    );
    $shopproIntegrationsController = new ShopproIntegrationsController(
        $template,
        $translator,
        $auth,
        $shopproIntegrationsRepository,
        new ShopproStatusMappingRepository($app->db()),
        $app->orderStatuses(),
        $cronRepository,
        $carrierDeliveryMappings,
        $allegroIntegrationRepository,
        $allegroOAuthClient,
        new AllegroApiClient(),
        $apaczkaIntegrationRepository,
        $apaczkaApiClient
    );
    $integrationsHubController = new IntegrationsHubController(
        $template,
        $translator,
        $auth,
        new IntegrationsRepository($app->db()),
        $allegroIntegrationRepository,
        $apaczkaIntegrationRepository,
        $inpostIntegrationRepository,
        $shopproIntegrationsRepository
    );
    $cronSettingsController = new CronSettingsController(
        $template,
        $translator,
        $auth,
        $cronRepository,
        (bool) $app->config('app.cron.run_on_web_default', false),
        (int) $app->config('app.cron.web_limit_default', 5)
    );
    $deliveryStatusMappingRepository = new DeliveryStatusMappingRepository($app->db());
    $deliveryStatusMappingController = new DeliveryStatusMappingController(
        $template,
        $translator,
        $auth,
        $deliveryStatusMappingRepository
    );
    $companySettingsRepository = new CompanySettingsRepository($app->db());
    $companySettingsController = new CompanySettingsController(
        $template,
        $translator,
        $auth,
        $companySettingsRepository
    );
    $receiptConfigController = new ReceiptConfigController(
        $template,
        $translator,
        $auth,
        $receiptConfigRepository
    );
    $emailMailboxRepository = new EmailMailboxRepository(
        $app->db(),
        new IntegrationSecretCipher((string) $app->config('app.integrations.secret', ''))
    );
    $emailMailboxController = new EmailMailboxController(
        $template,
        $translator,
        $auth,
        $emailMailboxRepository
    );
    $emailTemplateRepository = new EmailTemplateRepository($app->db());
    $emailTemplateController = new EmailTemplateController(
        $template,
        $translator,
        $auth,
        $emailTemplateRepository,
        $emailMailboxRepository
    );
    $automationRepository = new AutomationRepository($app->db());
    $automationExecutionLogRepository = new AutomationExecutionLogRepository($app->db());
    $automationController = new AutomationController(
        $template,
        $translator,
        $auth,
        $automationRepository,
        $automationExecutionLogRepository,
        $receiptConfigRepository
    );
    $variableResolver = new VariableResolver($shipmentPackageRepositoryForOrders);
    $attachmentGenerator = new AttachmentGenerator($receiptRepository, $receiptConfigRepository, $template);
    $emailSendingService = new EmailSendingService(
        $app->db(),
        $app->orders(),
        $emailTemplateRepository,
        $emailMailboxRepository,
        $variableResolver,
        $attachmentGenerator
    );
    $receiptService = new ReceiptService(
        $receiptRepository,
        $receiptConfigRepository,
        $companySettingsRepository,
        new OrdersRepository($app->db())
    );
    $automationService = new AutomationService(
        $automationRepository,
        $automationExecutionLogRepository,
        $emailSendingService,
        new OrdersRepository($app->db()),
        $companySettingsRepository,
        $receiptRepository,
        $receiptConfigRepository,
        $shipmentPackageRepositoryForOrders,
        $receiptService
    );
    $printJobRepository = new PrintJobRepository($app->db());
    $ordersController = new OrdersController($template, $translator, $auth, $app->orders(), $shipmentPackageRepositoryForOrders, $receiptRepository, $receiptConfigRepository, $emailSendingService, $emailTemplateRepository, $emailMailboxRepository, $app->basePath('storage'), $printJobRepository, $shopproIntegrationsRepository, $automationService);
    $receiptController = new ReceiptController(
        $template,
        $translator,
        $auth,
        $receiptRepository,
        $receiptConfigRepository,
        $companySettingsRepository,
        new OrdersRepository($app->db()),
        $automationService,
        $receiptService
    );
    $accountingController = new AccountingController(
        $template,
        $translator,
        $auth,
        $receiptRepository,
        $receiptConfigRepository
    );
    $allegroApiClient = new AllegroApiClient();
    $shipmentPackageRepository = new ShipmentPackageRepository($app->db());
    $shipmentService = new AllegroShipmentService(
        $allegroTokenManager,
        $allegroApiClient,
        $shipmentPackageRepository,
        $companySettingsRepository,
        new OrdersRepository($app->db())
    );
    $apaczkaShipmentService = new ApaczkaShipmentService(
        $apaczkaIntegrationRepository,
        $apaczkaApiClient,
        $shipmentPackageRepository,
        $companySettingsRepository,
        new OrdersRepository($app->db())
    );
    $inpostShipmentService = new InpostShipmentService(
        $inpostIntegrationRepository,
        $shipmentPackageRepository,
        $companySettingsRepository,
        new OrdersRepository($app->db())
    );
    $shipmentProviderRegistry = new ShipmentProviderRegistry([
        $shipmentService,
        $apaczkaShipmentService,
        $inpostShipmentService,
    ]);
    $shipmentController = new ShipmentController(
        $template,
        $translator,
        $auth,
        $app->orders(),
        $companySettingsRepository,
        $shipmentProviderRegistry,
        $shipmentPackageRepository,
        $automationService,
        $app->basePath('storage'),
        $carrierDeliveryMappings,
        $printJobRepository
    );
    $authMiddleware = new AuthMiddleware($auth);

    $publicCronHandler = static function (Request $request) use ($app, $cronRepository): Response {
        $token = trim((string) $request->input('token', ''));
        if ($token === '') {
            $token = trim((string) $request->input('tokenValue', ''));
            if (str_starts_with($token, 'token=')) {
                $token = substr($token, 6);
            }
        }

        $expectedToken = trim((string) $app->config('app.cron.public_token', ''));
        if ($expectedToken === '' || $token === '' || !hash_equals($expectedToken, $token)) {
            return Response::json([
                'ok' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        try {
            $limit = $cronRepository->getIntSetting(
                'cron_web_limit',
                (int) $app->config('app.cron.web_limit_default', 5),
                1,
                100
            );

            $factory = new CronHandlerFactory(
                $app->db(),
                (string) $app->config('app.integrations.secret', ''),
                $app->basePath()
            );
            $runner = $factory->build($cronRepository, $app->logger());
            $runner->run($limit);

            return Response::json([
                'ok' => true,
                'message' => 'Cron executed',
                'limit' => $limit,
                'timestamp' => date(DATE_ATOM),
            ]);
        } catch (\Throwable $exception) {
            $app->logger()->error('Public cron endpoint failed', [
                'message' => $exception->getMessage(),
                'path' => $request->path(),
            ]);

            $debug = (bool) $app->config('app.debug', false);
            return Response::json([
                'ok' => false,
                'message' => 'Cron execution failed',
                'error' => $debug ? $exception->getMessage() : null,
            ], 500);
        }
    };

    $router->get('/health', static fn (Request $request): Response => Response::json([
        'status' => 'ok',
        'app' => (string) $app->config('app.name', 'orderPRO'),
        'timestamp' => date(DATE_ATOM),
    ]));
    $router->get('/cron', $publicCronHandler);
    $router->get('/cron/{tokenValue}', $publicCronHandler);

    $router->get('/', static function (Request $request) use ($auth): Response {
        return $auth->check()
            ? Response::redirect('/settings/users')
            : Response::redirect('/login');
    });

    $router->get('/login', [$authController, 'showLogin']);
    $router->post('/login', [$authController, 'login']);
    $router->post('/logout', [$authController, 'logout'], [$authMiddleware]);

    $router->get('/users', static fn (Request $request): Response => Response::redirect('/settings/users'), [$authMiddleware]);
    $router->get('/orders', static fn (Request $request): Response => Response::redirect('/orders/list'), [$authMiddleware]);
    $router->get('/orders/list', [$ordersController, 'index'], [$authMiddleware]);
    $router->get('/orders/{id}', [$ordersController, 'show'], [$authMiddleware]);
    $router->post('/orders/{id}/status', [$ordersController, 'updateStatus'], [$authMiddleware]);
    $router->post('/orders/{id}/send-email', [$ordersController, 'sendEmail'], [$authMiddleware]);
    $router->post('/orders/{id}/email-preview', [$ordersController, 'emailPreview'], [$authMiddleware]);
    $router->post('/users', [$usersController, 'store'], [$authMiddleware]);
    $router->get('/settings/users', [$usersController, 'index'], [$authMiddleware]);
    $router->post('/settings/users', [$usersController, 'store'], [$authMiddleware]);
    $router->get('/settings', static fn (Request $request): Response => Response::redirect('/settings/users'), [$authMiddleware]);
    $router->get('/settings/database', [$settingsController, 'database'], [$authMiddleware]);
    $router->post('/settings/database/migrate', [$settingsController, 'migrate'], [$authMiddleware]);
    $router->get('/settings/statuses', [$settingsController, 'statuses'], [$authMiddleware]);
    $router->post('/settings/status-groups', [$settingsController, 'createStatusGroup'], [$authMiddleware]);
    $router->post('/settings/status-groups/update', [$settingsController, 'updateStatusGroup'], [$authMiddleware]);
    $router->post('/settings/status-groups/delete', [$settingsController, 'deleteStatusGroup'], [$authMiddleware]);
    $router->post('/settings/status-groups/reorder', [$settingsController, 'reorderStatusGroups'], [$authMiddleware]);
    $router->post('/settings/statuses/create', [$settingsController, 'createStatus'], [$authMiddleware]);
    $router->post('/settings/statuses/update', [$settingsController, 'updateStatus'], [$authMiddleware]);
    $router->post('/settings/statuses/delete', [$settingsController, 'deleteStatus'], [$authMiddleware]);
    $router->post('/settings/statuses/reorder', [$settingsController, 'reorderStatuses'], [$authMiddleware]);
    $router->get('/settings/cron', [$cronSettingsController, 'index'], [$authMiddleware]);
    $router->post('/settings/cron', [$cronSettingsController, 'save'], [$authMiddleware]);
    $router->get('/settings/integrations', [$integrationsHubController, 'index'], [$authMiddleware]);
    $router->get('/settings/integrations/allegro', [$allegroIntegrationController, 'index'], [$authMiddleware]);
    $router->post('/settings/integrations/allegro/save', [$allegroIntegrationController, 'save'], [$authMiddleware]);
    $router->post('/settings/integrations/allegro/settings/save', [$allegroIntegrationController, 'saveImportSettings'], [$authMiddleware]);
    $router->post('/settings/integrations/allegro/oauth/start', [$allegroIntegrationController, 'startOAuth'], [$authMiddleware]);
    $router->post('/settings/integrations/allegro/import-single', [$allegroIntegrationController, 'importSingleOrder'], [$authMiddleware]);
    $router->post('/settings/integrations/allegro/statuses/save', [$allegroStatusMappingController, 'saveStatusMapping'], [$authMiddleware]);
    $router->post('/settings/integrations/allegro/statuses/save-bulk', [$allegroStatusMappingController, 'saveStatusMappingsBulk'], [$authMiddleware]);
    $router->post('/settings/integrations/allegro/statuses/delete', [$allegroStatusMappingController, 'deleteStatusMapping'], [$authMiddleware]);
    $router->post('/settings/integrations/allegro/statuses/sync', [$allegroStatusMappingController, 'syncStatusesFromAllegro'], [$authMiddleware]);
    $router->post('/settings/integrations/allegro/delivery/save', [$allegroDeliveryMappingController, 'saveDeliveryMappings'], [$authMiddleware]);
    $router->get('/settings/integrations/allegro/oauth/callback', [$allegroIntegrationController, 'oauthCallback']);
    $router->get('/settings/integrations/apaczka', [$apaczkaIntegrationController, 'index'], [$authMiddleware]);
    $router->post('/settings/integrations/apaczka/save', [$apaczkaIntegrationController, 'save'], [$authMiddleware]);
    $router->post('/settings/integrations/apaczka/test', [$apaczkaIntegrationController, 'test'], [$authMiddleware]);
    $router->get('/settings/integrations/inpost', [$inpostIntegrationController, 'index'], [$authMiddleware]);
    $router->post('/settings/integrations/inpost/save', [$inpostIntegrationController, 'save'], [$authMiddleware]);
    $router->get('/settings/integrations/shoppro', [$shopproIntegrationsController, 'index'], [$authMiddleware]);
    $router->post('/settings/integrations/shoppro/save', [$shopproIntegrationsController, 'save'], [$authMiddleware]);
    $router->post('/settings/integrations/shoppro/test', [$shopproIntegrationsController, 'test'], [$authMiddleware]);
    $router->post('/settings/integrations/shoppro/statuses/save', [$shopproIntegrationsController, 'saveStatusMappings'], [$authMiddleware]);
    $router->post('/settings/integrations/shoppro/statuses/sync', [$shopproIntegrationsController, 'syncStatuses'], [$authMiddleware]);
    $router->post('/settings/integrations/shoppro/delivery/save', [$shopproIntegrationsController, 'saveDeliveryMappings'], [$authMiddleware]);
    $router->get('/settings/company', [$companySettingsController, 'index'], [$authMiddleware]);
    $router->post('/settings/company/save', [$companySettingsController, 'save'], [$authMiddleware]);
    $router->get('/settings/accounting', [$receiptConfigController, 'index'], [$authMiddleware]);
    $router->post('/settings/accounting/save', [$receiptConfigController, 'save'], [$authMiddleware]);
    $router->post('/settings/accounting/toggle', [$receiptConfigController, 'toggleStatus'], [$authMiddleware]);
    $router->post('/settings/accounting/delete', [$receiptConfigController, 'delete'], [$authMiddleware]);
    $router->get('/settings/email-mailboxes', [$emailMailboxController, 'index'], [$authMiddleware]);
    $router->post('/settings/email-mailboxes/save', [$emailMailboxController, 'save'], [$authMiddleware]);
    $router->post('/settings/email-mailboxes/delete', [$emailMailboxController, 'delete'], [$authMiddleware]);
    $router->post('/settings/email-mailboxes/toggle', [$emailMailboxController, 'toggleStatus'], [$authMiddleware]);
    $router->post('/settings/email-mailboxes/test', [$emailMailboxController, 'testConnection'], [$authMiddleware]);
    $router->get('/settings/email-templates', [$emailTemplateController, 'index'], [$authMiddleware]);
    $router->get('/settings/email-templates/create', [$emailTemplateController, 'create'], [$authMiddleware]);
    $router->get('/settings/email-templates/edit', [$emailTemplateController, 'edit'], [$authMiddleware]);
    $router->post('/settings/email-templates/save', [$emailTemplateController, 'save'], [$authMiddleware]);
    $router->post('/settings/email-templates/delete', [$emailTemplateController, 'delete'], [$authMiddleware]);
    $router->post('/settings/email-templates/duplicate', [$emailTemplateController, 'duplicate'], [$authMiddleware]);
    $router->post('/settings/email-templates/toggle', [$emailTemplateController, 'toggleStatus'], [$authMiddleware]);
    $router->post('/settings/email-templates/preview', [$emailTemplateController, 'preview'], [$authMiddleware]);
    $router->get('/settings/email-templates/variables', [$emailTemplateController, 'getVariables'], [$authMiddleware]);
    $router->get('/settings/automation', [$automationController, 'index'], [$authMiddleware]);
    $router->get('/settings/automation/create', [$automationController, 'create'], [$authMiddleware]);
    $router->post('/settings/automation/store', [$automationController, 'store'], [$authMiddleware]);
    $router->get('/settings/automation/edit', [$automationController, 'edit'], [$authMiddleware]);
    $router->post('/settings/automation/update', [$automationController, 'update'], [$authMiddleware]);
    $router->post('/settings/automation/delete', [$automationController, 'destroy'], [$authMiddleware]);
    $router->post('/settings/automation/duplicate', [$automationController, 'duplicate'], [$authMiddleware]);
    $router->post('/settings/automation/toggle', [$automationController, 'toggleStatus'], [$authMiddleware]);
    $router->get('/settings/delivery-status-mappings', [$deliveryStatusMappingController, 'index'], [$authMiddleware]);
    $router->post('/settings/delivery-status-mappings/save', [$deliveryStatusMappingController, 'save'], [$authMiddleware]);
    $router->post('/settings/delivery-status-mappings/save-bulk', [$deliveryStatusMappingController, 'saveBulk'], [$authMiddleware]);
    $router->post('/settings/delivery-status-mappings/reset', [$deliveryStatusMappingController, 'reset'], [$authMiddleware]);
    $router->post('/settings/delivery-status-mappings/reset-all', [$deliveryStatusMappingController, 'resetAll'], [$authMiddleware]);
    $router->get('/accounting', [$accountingController, 'index'], [$authMiddleware]);
    $router->post('/accounting/export', [$accountingController, 'export'], [$authMiddleware]);
    $router->get('/orders/{id}/receipt/create', [$receiptController, 'create'], [$authMiddleware]);
    $router->post('/orders/{id}/receipt/store', [$receiptController, 'store'], [$authMiddleware]);
    $router->get('/orders/{id}/receipt/{receiptId}', [$receiptController, 'show'], [$authMiddleware]);
    $router->get('/orders/{id}/receipt/{receiptId}/print', [$receiptController, 'printView'], [$authMiddleware]);
    $router->get('/orders/{id}/receipt/{receiptId}/pdf', [$receiptController, 'pdf'], [$authMiddleware]);
    $router->get('/orders/{id}/shipment/prepare', [$shipmentController, 'prepare'], [$authMiddleware]);
    $router->post('/orders/{id}/shipment/create', [$shipmentController, 'create'], [$authMiddleware]);
    $router->get('/orders/{id}/shipment/{packageId}/status', [$shipmentController, 'checkStatus'], [$authMiddleware]);
    $router->post('/orders/{id}/shipment/{packageId}/label', [$shipmentController, 'label'], [$authMiddleware]);
    $router->post('/orders/{id}/shipment/manual', [$shipmentController, 'createManual'], [$authMiddleware]);
    $router->post('/orders/{id}/payment/add', [$ordersController, 'addPayment'], [$authMiddleware]);

    // --- Printing module ---
    $printApiKeyRepository = new PrintApiKeyRepository($app->db());
    $apiKeyMiddleware = new ApiKeyMiddleware($printApiKeyRepository);
    $printApiController = new PrintApiController(
        $printJobRepository,
        $shipmentPackageRepository,
        $auth,
        $app->basePath('storage'),
        $shipmentProviderRegistry
    );
    $printSettingsController = new PrintSettingsController($template, $translator, $auth, $printApiKeyRepository, $printJobRepository);

    // Print API — session auth (from orderPRO UI)
    $router->post('/api/print/jobs', [$printApiController, 'createJob'], [$authMiddleware]);

    // Print API — API key auth (from Windows client)
    $router->get('/api/print/jobs/pending', [$printApiController, 'listPending'], [$apiKeyMiddleware]);
    $router->get('/api/print/jobs/{id}/download', [$printApiController, 'downloadLabel'], [$apiKeyMiddleware]);
    $router->post('/api/print/jobs/{id}/complete', [$printApiController, 'markComplete'], [$apiKeyMiddleware]);

    // Print settings
    $router->get('/settings/printing', [$printSettingsController, 'index'], [$authMiddleware]);
    $router->post('/settings/printing/keys/create', [$printSettingsController, 'createKey'], [$authMiddleware]);
    $router->post('/settings/printing/keys/{id}/delete', [$printSettingsController, 'deleteKey'], [$authMiddleware]);
    $router->post('/settings/printing/jobs/delete', [$printSettingsController, 'deleteJob'], [$authMiddleware]);

    // Shipment presets API
    $presetRepository = new ShipmentPresetRepository($app->db());
    $presetController = new ShipmentPresetController($presetRepository);

    $router->get('/api/shipment-presets', [$presetController, 'list'], [$authMiddleware]);
    $router->post('/api/shipment-presets', [$presetController, 'store'], [$authMiddleware]);
    $router->post('/api/shipment-presets/update', [$presetController, 'update'], [$authMiddleware]);
    $router->post('/api/shipment-presets/delete', [$presetController, 'destroy'], [$authMiddleware]);
};
