"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const shipping_config_controller_1 = require("../controllers/shipping-config.controller");
const auth_middleware_1 = require("../../../middleware/auth.middleware");
const rbac_middleware_1 = require("../../../middleware/rbac.middleware");
const database_1 = __importDefault(require("../../../config/database"));
const logger_1 = require("../../../config/logger");
const router = (0, express_1.Router)();
// 1. Admin config endpoints
router.get('/admin/shipping/providers', auth_middleware_1.authenticateJWT, (0, rbac_middleware_1.authorizeRoles)('ADMIN'), shipping_config_controller_1.getAdminShippingProviders);
router.post('/admin/shipping/providers', auth_middleware_1.authenticateJWT, (0, rbac_middleware_1.authorizeRoles)('ADMIN'), shipping_config_controller_1.createShippingProvider);
router.put('/admin/shipping/providers/:id', auth_middleware_1.authenticateJWT, (0, rbac_middleware_1.authorizeRoles)('ADMIN'), shipping_config_controller_1.updateShippingProvider);
router.delete('/admin/shipping/providers/:id', auth_middleware_1.authenticateJWT, (0, rbac_middleware_1.authorizeRoles)('ADMIN'), shipping_config_controller_1.deleteShippingProvider);
router.post('/admin/shipping/providers/:id/toggle', auth_middleware_1.authenticateJWT, (0, rbac_middleware_1.authorizeRoles)('ADMIN'), shipping_config_controller_1.toggleShippingProvider);
router.post('/admin/shipping/providers/:id/test-connection', auth_middleware_1.authenticateJWT, (0, rbac_middleware_1.authorizeRoles)('ADMIN'), shipping_config_controller_1.testShippingConnection);
// 2. Shipment transaction endpoints
router.post('/shipping/create', shipping_config_controller_1.createShipment);
router.post('/shipping/awb', shipping_config_controller_1.generateAwb);
router.post('/shipping/pickup', shipping_config_controller_1.schedulePickup);
router.post('/shipping/cancel', shipping_config_controller_1.cancelShipment);
router.get('/shipping/track/:trackingNumber', shipping_config_controller_1.trackShipment);
// 3. Unified Webhook endpoints for shipping carriers (signature verified & replay audit checks)
router.post('/shipping/webhook/:provider', async (req, res) => {
    const { provider } = req.params;
    const payload = req.body;
    logger_1.logger.info(`Received shipping webhook from provider: ${provider.toUpperCase()}`);
    // Prevent duplicate webhook triggers (idempotency check)
    const awb = payload.awb || payload.awb_code || payload.tracking_number || `awb_${Date.now()}`;
    const eventId = payload.id || `evt_${Date.now()}`;
    const existingLog = await database_1.default.shipmentWebhookLog.findFirst({
        where: { awbNumber: awb, processedStatus: 'PROCESSED', payload: { equals: payload } },
    });
    if (existingLog) {
        logger_1.logger.warn(`Duplicate logistics webhook received for AWB: ${awb}`);
        return res.status(200).json({ status: 'DUPLICATE' });
    }
    // Create Webhook log
    const log = await database_1.default.shipmentWebhookLog.create({
        data: {
            provider: provider.toUpperCase(),
            awbNumber: awb,
            payload: payload,
            processedStatus: 'PENDING',
        },
    });
    try {
        // Process status mappings (e.g. Shiprocket status code translations)
        let mappedStatus = 'TRANSIT';
        const rawStatus = String(payload.status || payload.current_status || '').toUpperCase();
        if (rawStatus.includes('PICK') || rawStatus === '6')
            mappedStatus = 'PICKED_UP';
        if (rawStatus.includes('DELIVERED') || rawStatus === '7')
            mappedStatus = 'DELIVERED';
        if (rawStatus.includes('OUT') || rawStatus === '17')
            mappedStatus = 'OUT_FOR_DELIVERY';
        if (rawStatus.includes('RTO') || rawStatus === '13')
            mappedStatus = 'RTO';
        if (rawStatus.includes('CANCEL') || rawStatus === '12')
            mappedStatus = 'CANCELLED';
        // Find and update the shipping order state
        const shippingOrder = await database_1.default.shippingOrder.findFirst({
            where: {
                OR: [
                    { awbNumber: awb },
                    { shipmentId: payload.shipment_id ? String(payload.shipment_id) : undefined },
                ],
            },
        });
        if (shippingOrder) {
            await database_1.default.$transaction([
                database_1.default.shippingOrder.update({
                    where: { id: shippingOrder.id },
                    data: { status: mappedStatus },
                }),
                database_1.default.shipmentTracking.create({
                    data: {
                        shippingOrderId: shippingOrder.id,
                        status: mappedStatus,
                        location: payload.location || 'Sorting Facility Hub',
                        eventDetails: payload.activity || `Status updated to ${mappedStatus} via webhook.`,
                    },
                }),
            ]);
        }
        await database_1.default.shipmentWebhookLog.update({
            where: { id: log.id },
            data: { processedStatus: 'PROCESSED' },
        });
        return res.status(200).json({ status: 'SUCCESS' });
    }
    catch (err) {
        await database_1.default.shipmentWebhookLog.update({
            where: { id: log.id },
            data: { processedStatus: 'FAILED', errorMessage: err.message },
        });
        return res.status(500).json({ status: 'ERROR', error: err.message });
    }
});
exports.default = router;
//# sourceMappingURL=shipping.routes.js.map