import { EntityManager, Not } from 'typeorm'
import { User } from '@things-factory/auth-base'
import { Domain } from '@things-factory/shell'
import { ORDER_INVENTORY_STATUS, OrderInventory, OrderToteItem } from '@things-factory/sales-base'

export const unsortItem = {
  async unsortItem(_: any, { orderToteItemId, reason }, context: any) {
    const { domain, user, tx }: { domain: Domain; user: User; tx: EntityManager } = context.state

    // Find the order tote item with relations
    const orderToteItem = (await tx.getRepository(OrderToteItem).findOne({
      where: { domain, id: orderToteItemId },
      relations: ['orderTote', 'orderInventory']
    })) as OrderToteItem | null

    if (!orderToteItem) {
      throw new Error('Order tote item not found')
    }

    // Check if tote is sealed - cannot undo if sealed
    if (orderToteItem.orderTote?.closedDate) {
      throw new Error('Cannot remove item from sealed tote.')
    }

    const orderInventory: 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 === ORDER_INVENTORY_STATUS.LOADING) {
      // Check if there are other order tote items for this order inventory
      const otherToteItems = await tx.getRepository(OrderToteItem).count({
        where: {
          domain,
          orderInventory: { id: orderInventory.id },
          id: Not(orderToteItemId)
        }
      })

      // Only revert to PICKED if this is the last tote item (no more sorted items)
      if (otherToteItems === 0) {
        newStatus = ORDER_INVENTORY_STATUS.SORTING
      }
    }

    // Update the order inventory
    await tx.getRepository(OrderInventory).update(orderInventory.id, {
      sortedQty: newSortedQty,
      status: newStatus,
      updatedAt: new Date(),
      updater: user
    })

    // Delete the order tote item
    await tx.getRepository(OrderToteItem).delete(orderToteItem.id)

    // Log the undo action if reason provided
    if (reason) {
      console.log(
        `[UNSORT] User ${user.name} removed ${qtyToRemove} items from tote ${orderToteItem.orderTote?.name}. Reason: ${reason}`
      )
    }

    return true
  }
}
