using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.DiscountShopCQ.Queries.GetUserCart;

public class GetUserCartQueryHandler : IRequestHandler<GetUserCartQuery, UserCartDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<UserCartDto> Handle(GetUserCartQuery request, CancellationToken cancellationToken)
    {
        var cartItems = await _context.DiscountShoppingCarts
            .Where(c => c.UserId == request.UserId)
            .Include(c => c.Product)
            .Select(c => new CartItemDto
            {
                CartItemId = c.Id,
                ProductId = c.ProductId,
                ProductTitle = c.Product.Title,
                ProductImagePath = c.Product.ThumbnailPath,
                UnitPrice = c.Product.Price,
                Count = c.Count,
                SubTotal = c.Product.Price * c.Count,
                MaxDiscountPercent = c.Product.MaxDiscountPercent,
                MaxDiscountAmount = (c.Product.Price * c.Count * c.Product.MaxDiscountPercent) / 100,
                MinPayable = c.Product.Price * c.Count - ((c.Product.Price * c.Count * c.Product.MaxDiscountPercent) / 100),
                RemainingStock = c.Product.RemainingCount,
                IsActive = c.Product.IsActive
            })
            .ToListAsync(cancellationToken);

        var totalAmount = cartItems.Sum(i => i.SubTotal);
        var maxDiscountAmount = cartItems.Sum(i => i.MaxDiscountAmount);
        var minPayableAmount = cartItems.Sum(i => i.MinPayable);

        return new UserCartDto
        {
            Items = cartItems,
            TotalAmount = totalAmount,
            MaxDiscountAmount = maxDiscountAmount,
            MinPayableAmount = minPayableAmount
        };
    }
}
