using CMSMicroservice.Application.Common.Exceptions;
using CMSMicroservice.Domain.Entities;
using CMSMicroservice.Domain.Enums;

namespace CMSMicroservice.Application.InventoryItemCQ.Commands.ReleaseReservedInventory;

public class ReleaseReservedInventoryCommandHandler : IRequestHandler<ReleaseReservedInventoryCommand, ReleaseReservedInventoryResponseDto>
{
    private readonly IApplicationDbContext _context;

    public ReleaseReservedInventoryCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<ReleaseReservedInventoryResponseDto> Handle(ReleaseReservedInventoryCommand request, CancellationToken cancellationToken)
    {
        var item = await _context.InventoryItems
            .FirstOrDefaultAsync(i => i.Id == request.Id, cancellationToken);

        if (item == null)
        {
            throw new NotFoundException(nameof(Domain.Entities.InventoryItem), request.Id);
        }

        if (item.ReservedQuantity < request.Quantity)
        {
            throw new InvalidOperationException($"Cannot release more than reserved. Reserved: {item.ReservedQuantity}, Requested: {request.Quantity}");
        }

        item.ReservedQuantity -= request.Quantity;

        // ثبت حرکت موجودی
        var stockMovement = new StockMovement
        {
            InventoryItemId = item.Id,
            MovementType = StockMovementType.Released,
            Quantity = request.Quantity,
            QuantityBefore = item.Quantity,
            QuantityAfter = item.Quantity,
            Note = "Reservation released",
            ReferenceNumber = request.ReferenceNumber ?? $"REL-{DateTime.UtcNow:yyyyMMddHHmmss}",
            OrderId = request.OrderId,
            DiscountOrderId = request.DiscountOrderId,
            PerformedByUserId = request.PerformedByUserId
        };

        await _context.StockMovements.AddAsync(stockMovement, cancellationToken);
        await _context.SaveChangesAsync(cancellationToken);

        return new ReleaseReservedInventoryResponseDto { Success = true };
    }
}
