using LiteCqrs;
using TeleWave.Api.Common;
using TeleWave.Application.Settings;
using TeleWave.Application.Settings.GetSiteSettings;
using TeleWave.Application.Settings.UpdateSiteSettings;
using TeleWave.Infrastructure.Identity;

namespace TeleWave.Api.Endpoints;

public static class SettingsEndpoints
{
    public static IEndpointRouteBuilder MapSettingsEndpoints(this IEndpointRouteBuilder app)
    {
        var admin = app.MapGroup("/api/admin/settings")
            .WithTags("Admin.Settings")
            .RequireAuthorization(policy => policy.RequireRole(RoleNames.Admin));

        admin.MapGet("", GetSettings).Produces<SiteSettingsDto>();
        admin.MapPut("", UpdateSettings).Produces(StatusCodes.Status204NoContent);

        return app;
    }

    private static async Task<IResult> GetSettings(
        ISender sender,
        CancellationToken cancellationToken
    )
    {
        var settings = await sender.Send(new GetSiteSettingsQuery(), cancellationToken);
        return Results.Ok(settings);
    }

    private static async Task<IResult> UpdateSettings(
        UpdateSiteSettingsBody body,
        ISender sender,
        CancellationToken cancellationToken
    )
    {
        var result = await sender.Send(
            new UpdateSiteSettingsCommand(
                body.RegistrationEnabled,
                body.PreferredAudioLanguages ?? "",
                body.ChannelNumbersEnabled
            ),
            cancellationToken
        );
        return result.ToHttpResult();
    }
}

public sealed record UpdateSiteSettingsBody(
    bool RegistrationEnabled,
    string? PreferredAudioLanguages,
    bool ChannelNumbersEnabled
);
