using static FastExpressionCompiler.ExpressionCompiler;
using TypedResults = Microsoft.AspNetCore.Http.TypedResults;

namespace NetinaShop.Api.Controller;

public class PaymentController : ICarterModule
{

    public virtual void AddRoutes(IEndpointRouteBuilder app)
    {
        var group = app.NewVersionedApi("AccountingPayment")
            .MapGroup($"api/accounting/pay");

        group.MapGet("", GetAllAsync)
            .WithDisplayName("GetPayments")
            .RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
            .HasApiVersion(1.0);

        //group.MapGet("{id}", GetAsync)
        //    .WithDisplayName("GetShipping")
        //    .RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser())
        //    .HasApiVersion(1.0);

        group.MapGet("verify", VerifyPaymentAsync)
            .HasApiVersion(1.0);
    }

    // GET:Get All Entity
    public async Task<IResult> GetAllAsync([FromQuery] int page, IMediator mediator, CancellationToken cancellationToken)
        => TypedResults.Ok(await mediator.Send(new GetPaymentsQuery(page), cancellationToken));

    // GET:Get An Entity By Id
    public async Task<IResult> GetAsync(Guid id, IMediator mediator, CancellationToken cancellationToken)
        => TypedResults.Ok(await mediator.Send(new GetShippingQuery(id), cancellationToken));

    // POST:Create Entity
    public async Task<IResult> VerifyPaymentAsync([FromQuery] string Authority, [FromQuery] string Status, IPaymentService paymentService,ILogger<PaymentController> logger, CancellationToken cancellationToken)
    {
        try
        {
            if (Status == "OK")
            {
                var result = await paymentService.VerifyPaymentAsync(authority: Authority, cancellationToken);
                return TypedResults.Redirect($"https://vesmook.com/purchase-callback?refid={result.Item1}&paymentStatus=true&factorNumber={result.Item2}", true);
            }
            else
            {
                return TypedResults.Redirect($"https://vesmook.com/purchase-callback?refid=0&paymentStatus=false&factorNumber=0", true);
            }
        }
        catch (Exception e)
        {
            logger.LogError(e.Message);
            return TypedResults.Redirect("");
        }
    }

}