"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unsortItem = void 0;
const typeorm_1 = require("typeorm");
const sales_base_1 = require("@things-factory/sales-base");
exports.unsortItem = {
    async unsortItem(_, { orderToteItemId, reason }, context) {
        var _a, _b;
        const { domain, user, tx } = context.state;
        // Find the order tote item with relations
        const orderToteItem = (await tx.getRepository(sales_base_1.OrderToteItem).findOne({
            where: { domain, id: orderToteItemId },
            relations: ['orderTote', 'orderInventory']
        }));
        if (!orderToteItem) {
            throw new Error('Order tote item not found');
        }
        // Check if tote is sealed - cannot undo if sealed
        if ((_a = orderToteItem.orderTote) === null || _a === void 0 ? void 0 : _a.closedDate) {
            throw new Error('Cannot remove item from sealed tote.');
        }
        const orderInventory = orderToteItem.orderInventory;
        const qtyToRemove = orderToteItem.qty;
        if (!orderInventory) {
            throw new Error('Associated order inventory not found');
        }
        // Validate that we can reduce the sorted quantity
        if (orderInventory.sortedQty < qtyToRemove) {
            throw new Error(`Cannot remove ${qtyToRemove} items. Current sorted quantity is ${orderInventory.sortedQty}`);
        }
        // Calculate new sorted quantity
        const newSortedQty = orderInventory.sortedQty - qtyToRemove;
        // Determine new status - revert to PICKED if no more sorted items
        let newStatus = orderInventory.status;
        if (newSortedQty === 0 && orderInventory.status === sales_base_1.ORDER_INVENTORY_STATUS.LOADING) {
            // Check if there are other order tote items for this order inventory
            const otherToteItems = await tx.getRepository(sales_base_1.OrderToteItem).count({
                where: {
                    domain,
                    orderInventory: { id: orderInventory.id },
                    id: (0, typeorm_1.Not)(orderToteItemId)
                }
            });
            // Only revert to PICKED if this is the last tote item (no more sorted items)
            if (otherToteItems === 0) {
                newStatus = sales_base_1.ORDER_INVENTORY_STATUS.SORTING;
            }
        }
        // Update the order inventory
        await tx.getRepository(sales_base_1.OrderInventory).update(orderInventory.id, {
            sortedQty: newSortedQty,
            status: newStatus,
            updatedAt: new Date(),
            updater: user
        });
        // Delete the order tote item
        await tx.getRepository(sales_base_1.OrderToteItem).delete(orderToteItem.id);
        // Log the undo action if reason provided
        if (reason) {
            console.log(`[UNSORT] User ${user.name} removed ${qtyToRemove} items from tote ${(_b = orderToteItem.orderTote) === null || _b === void 0 ? void 0 : _b.name}. Reason: ${reason}`);
        }
        return true;
    }
};
//# sourceMappingURL=unsort-item.js.map