namespace Netina.Core.EntityServices.OrderHandlers;

public class CalculateOrderCommandHandler(IRepositoryWrapper repositoryWrapper, IMediator mediator,ISettingService settingService) : IRequestHandler<CalculateOrderCommand,Order>
{

    public async Task<Order> Handle(CalculateOrderCommand request, CancellationToken cancellationToken)
    {
        var setting = await settingService.GetSettingAsync("ShopSetting", cancellationToken);
        double taxesFee = 9;
        if (setting is ShopSetting shopSetting)
            taxesFee = shopSetting.TaxesFee;
        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 - (discountCodePrice + productDiscountPrice)) + totalPackingPrice + servicePrice) / 100) * taxesFee;


        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;
    }
}