using MediatR;
using NetinaShop.Domain.CommandQueries.Commands;
using NetinaShop.Domain.CommandQueries.Queries;
using NetinaShop.Domain.Enums;
using NetinaShop.Infrastructure.Models.RestApi.Zarinpal;

namespace NetinaShop.Infrastructure.Services;

public class ZarinpalService : IPaymentService
{
    private readonly IRestApiWrapper _restApiWrapper;
    private readonly IMediator _mediator;
    private readonly SiteSettings _siteSettings;
    public ZarinpalService(IRestApiWrapper restApiWrapper,IOptionsSnapshot<SiteSettings> snapshot,IMediator mediator)
    {
        _restApiWrapper = restApiWrapper;
        _mediator = mediator;
        _siteSettings = snapshot.Value;
    }
    public async Task<string> GetPaymentLinkAsync(double amount,string factorNumber, Guid orderId, Guid userId, string phoneNumber , string fullName , CancellationToken cancellationToken = default)
    {
        var request = new ZarinaplPaymentLinkRequest
        {
            description = $"پرداخت {amount.ToString("N0")} ریال توسط {fullName} با شماره تماس {phoneNumber} برای سفارش با شماره {factorNumber}",
            amount = (int)amount,
            callback_url = Path.Combine("https://api.vesmook.com", "api", "accounting", "pay", "verify"),
            merchant_id = "4292b845-b510-4d1d-8ee2-097499b198e5",
            metadata = new ZarinaplPaymentLinkRequestMetadata { mobile = phoneNumber }
        };
        var response = await _restApiWrapper.ZarinpalRestApi.GetPaymentLinkAsync(request);
        if (response.data.code != 100)
            throw new AppException($"Exception in get link from zarinpal | {response.data.message}");


        var createPaymentResult = await _mediator.Send(new CreateOrUpdatePaymentCommand(null,factorNumber, amount, 
            request.description, string.Empty, string.Empty,
                response.data.authority, PaymentType.Online,PaymentStatus.InPaymentGateway, orderId, userId), cancellationToken);

        string link = $"https://www.zarinpal.com/pg/StartPay/{response.data.authority}";
        return link;
    }

    public async Task<Tuple<string,string>> VerifyPaymentAsync(string authority, CancellationToken cancellationToken = default)
    {
        var payment = await _mediator.Send(new GetPaymentQuery(Authority: authority), cancellationToken);
        var request = new ZarinaplVerifyPaymentRequest
        {
            amount = (int)payment.Amount,
            authority = payment.Authority,
            merchant_id = "4292b845-b510-4d1d-8ee2-097499b198e5"
        };
        var response = await _restApiWrapper.ZarinpalRestApi.VerifyPaymentAsync(request);
        if (response.data.code != 100)
            throw new AppException($"Exception in get link from zarinpal | {response.data.message}");

        payment.Status = PaymentStatus.Paid;
        payment.CardPan = response.data.card_pan;
        payment.TransactionCode = response.data.ref_id.ToString();

        await _mediator.Send(
            new CreateOrUpdatePaymentCommand(payment.Id, payment.FactorNumber, payment.Amount, payment.Description,
                payment.TransactionCode, payment.CardPan, payment.Authority, payment.Type, payment.Status,
                payment.OrderId, payment.UserId), cancellationToken);

        await _mediator.Send(new SubmitOrderPaymentCommand(payment.OrderId, OrderPaymentMethod.OnlinePayment, true),cancellationToken);

        return new Tuple<string, string>(payment.TransactionCode,payment.FactorNumber);
    }
}