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

namespace CMSMicroservice.Application.InventoryItemCQ.Commands.IncreaseInventory;

public class IncreaseInventoryCommandHandler : IRequestHandler<IncreaseInventoryCommand, IncreaseInventoryResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<IncreaseInventoryResponseDto> Handle(IncreaseInventoryCommand 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;
        item.Quantity += request.Quantity;
        item.LastRestockedAt = DateTime.UtcNow;

        // ثبت حرکت موجودی
        var stockMovement = new StockMovement
        {
            InventoryItemId = item.Id,
            MovementType = StockMovementType.Restock,
            Quantity = request.Quantity,
            QuantityBefore = previousQuantity,
            QuantityAfter = item.Quantity,
            Note = request.Note ?? "Stock increased",
            ReferenceNumber = request.ReferenceNumber ?? $"ADD-{DateTime.UtcNow:yyyyMMddHHmmss}",
            PerformedByUserId = request.PerformedByUserId
        };

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

        // همگام‌سازی با Product.RemainingCount یا DiscountProduct.RemainingCount
        if (item.ProductType == ProductType.RegularProduct && item.ProductId.HasValue)
        {
            var product = await _context.Products.FindAsync(new object[] { item.ProductId.Value }, cancellationToken);
            if (product != null)
            {
                product.RemainingCount = item.Quantity;
            }
        }
        else if (item.ProductType == ProductType.DiscountProduct && item.DiscountProductId.HasValue)
        {
            var discountProduct = await _context.DiscountProducts.FindAsync(
                new object[] { item.DiscountProductId.Value }, cancellationToken);
            if (discountProduct != null)
            {
                discountProduct.RemainingCount = item.Quantity;
            }
        }

        await _context.SaveChangesAsync(cancellationToken);

        return new IncreaseInventoryResponseDto
        {
            Success = true,
            NewQuantity = item.Quantity
        };
    }
}
