using Netina.Domain.MartenEntities.Settings;

namespace Netina.Api.Controllers;

public class MarketerController : ICarterModule
{
    public void AddRoutes(IEndpointRouteBuilder app)
    {
        var group = app.NewVersionedApi("Marketer")
            .MapGroup("api/marketer")
            .RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser());

        group.MapGet("", GetMarketersAsync)
            .WithDisplayName("GetAllMarketers")
            .RequireAuthorization(builder=>builder.RequireClaim(CustomClaimType.Permission,ApplicationPermission.ManageUsers , ApplicationPermission.ViewUsers))
            .HasApiVersion(1.0);

        group.MapGet("profile", GetMarketerProfileAsync)
            .WithDisplayName("GetAllMarketers")
            .HasApiVersion(1.0);

        group.MapPost("signup", SignUpMarketerAsync)
            .WithDisplayName("SignUpMarketer")
            .HasApiVersion(1.0);

        group.MapGet("signup/contract", GetSignUpMarketerContractAsync)
            .WithDisplayName("SignUpMarketerContract")
            .HasApiVersion(1.0);
    }

    private async Task<IResult> GetMarketerProfileAsync(IMediator mediator, CancellationToken cancellationToken)
        => TypedResults.Ok(await mediator.Send(new GetMarketerProfileQuery(), cancellationToken));

    private async Task<IResult> GetSignUpMarketerContractAsync([FromServices] ISettingService settingService,CancellationToken cancellationToken)
    {
        var setting = await settingService.GetSettingAsync(nameof(MarketerSetting), cancellationToken);
        if (setting is MarketerSetting marketerSetting)
            return TypedResults.Ok(marketerSetting.ContractTerms);
        throw new AppException("MarketerSetting not found");
    }

    private async Task<IResult> SignUpMarketerAsync([FromBody] SignUpMarketerCommand request, [FromServices] IMediator mediator, CancellationToken cancellationToken)
        => TypedResults.Ok(await mediator.Send(request, cancellationToken));

    private async Task<IResult> GetMarketersAsync([FromQuery] int page, [FromServices] IMediator mediator, CancellationToken cancellationToken)
        => TypedResults.Ok(await mediator.Send(new GetMarketersQuery(page), cancellationToken));
}