using Netina.Common.Models.Api;
using Netina.Common.Models.Exception;
using Netina.Core.Abstracts;
using Netina.Domain.CommandQueries.Commands;
using Netina.Domain.Dtos.ResponseDtos;
using Netina.Domain.Entities.Orders;
using Netina.Domain.Enums;
using Netina.Repository.Repositories.Base.Contracts;

namespace Netina.Core.EntityServices.OrderBagHandlers;

public class SubmitOrderPaymentCommandHandler : IRequestHandler<SubmitOrderPaymentCommand , SubmitOrderPaymentResponseDto>
{
    private readonly IMediator _mediator;
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly IPaymentService _paymentService;

    public SubmitOrderPaymentCommandHandler(IMediator mediator, IRepositoryWrapper repositoryWrapper, IPaymentService paymentService)
    {
        _mediator = mediator;
        _repositoryWrapper = repositoryWrapper;
        _paymentService = paymentService;
    }
    public async Task<SubmitOrderPaymentResponseDto> Handle(SubmitOrderPaymentCommand request, CancellationToken cancellationToken)
    {
        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);
            }
            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);
        }
        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);
        }

        return response;

    }
}