namespace Netina.Core.EntityServices.OrderBagHandlers;

public class SubmitOrderPaymentCommandHandler(IMediator mediator, IRepositoryWrapper repositoryWrapper, IPaymentService paymentService, ISmsService smsService, IOptionsSnapshot<SiteSettings> optionsSnapshot)
    : IRequestHandler<SubmitOrderPaymentCommand , SubmitOrderPaymentResponseDto>
{
    public async Task<SubmitOrderPaymentResponseDto> Handle(SubmitOrderPaymentCommand request, CancellationToken cancellationToken)
    {
        var _siteSetting = optionsSnapshot.Value;
        await mediator.Send(new CalculateOrderCommand(request.OrderId, true), cancellationToken);

        var order = await repositoryWrapper.SetRepository<Order>()
            .TableNoTracking
            .Where(o => o.Id == request.OrderId)
            .FirstOrDefaultAsync(cancellationToken);

        if (order == null)
            throw new AppException("Order not found", ApiResultStatusCode.NotFound);

        var response = new SubmitOrderPaymentResponseDto();

        if (request.PaymentMethod == OrderPaymentMethod.OnlinePayment)
        {
            if (request.HasPaid)
            {
                response.NeedToPayOnline = false;
                order.SetOrderPayment(request.PaymentMethod);
                repositoryWrapper.SetRepository<Order>().Update(order);
                await repositoryWrapper.SaveChangesAsync(cancellationToken);
                if (!_siteSetting.Manager.Phone.IsNullOrEmpty())
                    await smsService.SendLookUpAsync(_siteSetting.Manager.Phone, "manager-submitOrder",order.FactorCode,null,null, $"{_siteSetting.Manager.FirstName} {_siteSetting.Manager.LastName}");
            }
            else
            {
                response.NeedToPayOnline = true;
                var orderSDto = await repositoryWrapper.SetRepository<Order>()
                    .TableNoTracking
                    .Where(o => o.Id == request.OrderId)
                    .Select(OrderMapper.ProjectToSDto)
                    .FirstOrDefaultAsync(cancellationToken);
                if (orderSDto == null)
                    throw new AppException("Order not found", ApiResultStatusCode.NotFound);
                response.PaymentUrl = await paymentService.GetPaymentLinkAsync(orderSDto.TotalPrice, orderSDto.FactorCode, orderSDto.Id, orderSDto.CustomerId, orderSDto.CustomerPhoneNumber, orderSDto.CustomerFullName, cancellationToken);
            }
        }
        else if (request.PaymentMethod == OrderPaymentMethod.PayOnDoor)
        {
            response.NeedToPayOnline = false;
            order.SetOrderPayment(request.PaymentMethod);
            repositoryWrapper.SetRepository<Order>().Update(order);
            await repositoryWrapper.SaveChangesAsync(cancellationToken);

            await mediator.Send(new CreateOrUpdatePaymentCommand(null,order.FactorCode, order.TotalPrice,
                $"پرداخت نقدی سفارش {order.FactorCode}", string.Empty, string.Empty, string.Empty,
                PaymentType.PayOnDoor, PaymentStatus.Paid, order.Id
                , order.CustomerId), cancellationToken);

            if (!_siteSetting.Manager.Phone.IsNullOrEmpty())
                await smsService.SendLookUpAsync(_siteSetting.Manager.Phone, "manager-submitOrder", order.FactorCode, null, null, $"{_siteSetting.Manager.FirstName} {_siteSetting.Manager.LastName}");
        }
        else if (request.PaymentMethod == OrderPaymentMethod.CardTransfer)
        {
            response.NeedToPayOnline = false;
            order.SetOrderPayment(request.PaymentMethod);
            repositoryWrapper.SetRepository<Order>().Update(order);
            await repositoryWrapper.SaveChangesAsync(cancellationToken);

            await mediator.Send(new CreateOrUpdatePaymentCommand(null,order.FactorCode, order.TotalPrice,
                $"پرداخت نقدی سفارش {order.FactorCode}", string.Empty, string.Empty, string.Empty,
                PaymentType.CardTransfer, PaymentStatus.Paid, order.Id
                , order.CustomerId), cancellationToken);

            if (!_siteSetting.Manager.Phone.IsNullOrEmpty())
                await smsService.SendLookUpAsync(_siteSetting.Manager.Phone, "manager-submitOrder", order.FactorCode, null, null, $"{_siteSetting.Manager.FirstName} {_siteSetting.Manager.LastName}");
        }

        return response;

    }
}