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

namespace CMSMicroservice.Application.InventoryItemCQ.Commands.UpdateInventoryQuantity;

public class UpdateInventoryQuantityCommandHandler : IRequestHandler<UpdateInventoryQuantityCommand, UpdateInventoryQuantityResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<UpdateInventoryQuantityResponseDto> Handle(UpdateInventoryQuantityCommand 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);
        }

        var previousQuantity = item.Quantity;
        var difference = request.NewQuantity - previousQuantity;

        item.Quantity = request.NewQuantity;

        // ثبت حرکت موجودی
        var movementType = difference > 0 ? StockMovementType.AdjustmentPlus : StockMovementType.AdjustmentMinus;

        var stockMovement = new StockMovement
        {
            InventoryItemId = item.Id,
            MovementType = movementType,
            Quantity = Math.Abs(difference),
            QuantityBefore = previousQuantity,
            QuantityAfter = request.NewQuantity,
            Note = request.Note ?? "Manual quantity adjustment",
            ReferenceNumber = request.ReferenceNumber ?? $"ADJ-{DateTime.UtcNow:yyyyMMddHHmmss}",
            PerformedByUserId = request.PerformedByUserId
        };

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

        return new UpdateInventoryQuantityResponseDto
        {
            Success = true,
            PreviousQuantity = previousQuantity,
            NewQuantity = request.NewQuantity
        };
    }
}
