using System.Text.Json;

namespace Netina.Api.Controllers;

public class SettingController : ICarterModule
{
    public void AddRoutes(IEndpointRouteBuilder app)
    {
        var group = app.NewVersionedApi("Setting")
            .MapGroup("api/setting");

        group.MapGet("{settingName}", GetSettingAsync)
            .WithDisplayName("GetSetting")
            .RequireAuthorization(builder=>builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser().RequireClaim(CustomClaimType.Permission, ApplicationPermission.ViewSettings,ApplicationPermission.ManageSettings))
            .HasApiVersion(1.0);

        group.MapPost("{settingName}", PostSettingAsync)
            .WithDisplayName("PostSettingAsync")
            .RequireAuthorization(builder => builder.AddAuthenticationSchemes("Bearer").RequireAuthenticatedUser().RequireClaim(CustomClaimType.Permission, ApplicationPermission.ManageSettings))
            .HasApiVersion(1.0);
    }

    public async Task<IResult> GetSettingAsync(string settingName, [FromServices] ISettingService settingService, CancellationToken cancellationToken)
        => TypedResults.Ok(await settingService.GetSettingAsync(settingName, cancellationToken));

    public async Task<IResult> PostSettingAsync(string settingName, [FromBody]JsonDocument settingObj, [FromServices]ISettingService settingService, CancellationToken cancellationToken)
    {
        await settingService.CreateOrUpdateSettingAsync(settingName, settingObj,cancellationToken);
        return TypedResults.Ok();
    }
}