namespace NetinaShop.Core.EntityServices.OrderHandlers;

public class CalculateOrderCommandHandler : IRequestHandler<CalculateOrderCommand,Order>
{
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly IMediator _mediator;
    private readonly ShopSettings _shopSettings;

    public CalculateOrderCommandHandler(IRepositoryWrapper repositoryWrapper, IMediator mediator, IOptionsSnapshot<ShopSettings> snapshot)
    {
        _repositoryWrapper = repositoryWrapper;
        _mediator = mediator;
        _shopSettings = snapshot.Value;
    }

    public async Task<Order> Handle(CalculateOrderCommand request, CancellationToken cancellationToken)
    {
        var order = await _mediator.Send(new GetOrderQuery(request.OrderId), cancellationToken);
        if (order.OrderStatus != OrderStatus.OrderBag)
            throw new AppException("Order is not in bag status and cant be calculate", ApiResultStatusCode.BadRequest);
        var totalProductPrice = order.OrderProducts.Sum(op => op.ProductFee * op.Count);
        var totalPackingPrice = order.OrderProducts.Sum(op => op.PackingCost);

        //var servicePrice = _shopSettings.ServiceIsPercent
        //    ? (totalProductPrice / 100) * _shopSettings.ServiceFee
        //    : _shopSettings.ServiceFee;

        var servicePrice = 0;
        var deliveryPrice = order.OrderDelivery?.DeliveryCost ?? 0;
        double productDiscountPrice = order.OrderProducts.Sum(op=>(op.ProductFee - op.ProductFeeWithDiscount) * op.Count);
        double discountCodePrice = 0;
        if (!order.DiscountCode.IsNullOrEmpty())
            discountCodePrice += await _mediator.Send(new CalculateOrderDiscountCommand(order.DiscountCode, order),cancellationToken);

        //var taxesPrice = (((totalProductPrice - discountPrice) + totalPackingPrice + servicePrice) / 100) * _shopSettings.TaxesFee;

        var taxesPrice = 0;

        order.SetTotalPrice(totalProductPrice, totalPackingPrice, servicePrice, deliveryPrice, productDiscountPrice, discountCodePrice, taxesPrice);
        order.OrderProducts.Clear();
        order.OrderDelivery = null;
        _repositoryWrapper.SetRepository<Order>().Update(order);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        return order;
    }
}