using LiteCqrs;
using TeleWave.Api.Common;
using TeleWave.Application.Maintenance.ClearAllMedia;
using TeleWave.Application.Maintenance.DeleteAllShows;
using TeleWave.Application.Maintenance.DeleteShowMedia;
using TeleWave.Infrastructure.Identity;

namespace TeleWave.Api.Endpoints;

public static class MaintenanceEndpoints
{
    public static IEndpointRouteBuilder MapMaintenanceEndpoints(this IEndpointRouteBuilder app)
    {
        var admin = app.MapGroup("/api/admin/maintenance")
            .WithTags("Admin.Maintenance")
            .RequireAuthorization(policy => policy.RequireRole(RoleNames.Admin));

        admin.MapPost("/clear-media", ClearMedia).Produces<int>();
        admin.MapPost("/clear-shows", ClearShows).Produces<int>();
        admin.MapPost("/shows/{showId:guid}/clear-media", ClearShowMedia).Produces<int>();

        return app;
    }

    private static async Task<IResult> ClearMedia(
        ISender sender,
        CancellationToken cancellationToken
    )
    {
        var result = await sender.Send(new ClearAllMediaCommand(), cancellationToken);
        return result.ToHttpResult();
    }

    private static async Task<IResult> ClearShows(
        ISender sender,
        CancellationToken cancellationToken
    )
    {
        var result = await sender.Send(new DeleteAllShowsCommand(), cancellationToken);
        return result.ToHttpResult();
    }

    private static async Task<IResult> ClearShowMedia(
        Guid showId,
        ISender sender,
        CancellationToken cancellationToken
    )
    {
        var result = await sender.Send(new DeleteShowMediaCommand(showId), cancellationToken);
        return result.ToHttpResult();
    }
}
