using Microsoft.Extensions.Options;
using TypedResults = Microsoft.AspNetCore.Http.TypedResults;

namespace Netina.Api.Controllers;

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().RequireClaim(CustomClaimType.Permission, ApplicationPermission.ViewPayments))
            .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, IOptionsSnapshot<SiteSettings> optionsSnapshot, ILogger<PaymentController> logger, CancellationToken cancellationToken)
    {
        var siteUrl = optionsSnapshot.Value.WebSiteUrl;
        if (Status == "OK")
        {
            var result = await paymentService.VerifyPaymentAsync(authority: Authority, cancellationToken);
            return TypedResults.Redirect($"{siteUrl}/purchase-callback?refid={result.Item1}&paymentStatus=true&factorNumber={result.Item2}", true);
        }
        else
        {
            return TypedResults.Redirect($"{siteUrl}/purchase-callback?refid=0&paymentStatus=false&factorNumber=0", true);
        }
    }

}