using CMSMicroservice.Domain.Enums;

namespace CMSMicroservice.Application.InventoryItemCQ.Queries.GetInventoryByProduct;

public class GetInventoryByProductQueryHandler : IRequestHandler<GetInventoryByProductQuery, GetInventoryByProductResponseDto?>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetInventoryByProductResponseDto?> Handle(GetInventoryByProductQuery request, CancellationToken cancellationToken)
    {
        var query = _context.InventoryItems
            .AsNoTracking()
            .Include(i => i.Warehouse)
            .Include(i => i.Product)
            .Include(i => i.DiscountProduct)
            .AsQueryable();

        // فیلتر بر اساس نوع محصول
        if (request.ProductType == ProductType.RegularProduct)
        {
            query = query.Where(i => i.ProductId == request.ProductId);
        }
        else
        {
            query = query.Where(i => i.DiscountProductId == request.ProductId);
        }

        // فیلتر بر اساس انبار (اختیاری)
        if (request.WarehouseId.HasValue)
        {
            query = query.Where(i => i.WarehouseId == request.WarehouseId.Value);
        }

        var item = await query
            .Select(i => new GetInventoryByProductResponseDto
            {
                Id = i.Id,
                ProductId = i.ProductId,
                DiscountProductId = i.DiscountProductId,
                ProductType = i.ProductType,
                WarehouseId = i.WarehouseId,
                WarehouseName = i.Warehouse != null ? i.Warehouse.Name : null,
                ProductTitle = i.Product != null ? i.Product.Title : (i.DiscountProduct != null ? i.DiscountProduct.Title : null),
                ProductPrice = i.Product != null ? i.Product.Price : (i.DiscountProduct != null ? i.DiscountProduct.Price : 0),
                Quantity = i.Quantity,
                ReservedQuantity = i.ReservedQuantity,
                AvailableQuantity = i.AvailableQuantity,
                LowStockThreshold = i.LowStockThreshold,
                MaxStockLevel = i.MaxStockLevel,
                LastRestockedAt = i.LastRestockedAt,
                LastSoldAt = i.LastSoldAt,
                Created = i.Created
            })
            .FirstOrDefaultAsync(cancellationToken);

        return item;
    }
}
