using Indotalent.ConfigBackEnd.Extensions;
using Indotalent.Features.Serilogs.Database;
using Indotalent.Shared.Models;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;

namespace Indotalent.Features.Serilogs;

public static class SerilogsEndpoint
{
    public static void MapSerilogsEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/serilog-logs").WithTags("Serilogs")
            .RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser());

        group.MapGet("/", async ([AsParameters] ApiRequest request, IMediator mediator) =>
        {
            var result = await mediator.Send(new GetSerilogLogsPagedListQuery(request));
            return result.ToApiResponse("Database logs retrieved successfully");
        })
        .WithName("GetSerilogLogsList")
        .WithTags("Serilogs");

        group.MapGet("/{id:int}", async (int id, IMediator mediator) =>
        {
            var result = await mediator.Send(new GetSerilogLogsByIdQuery(id));

            return result.ToApiResponse(result is not null
                ? "Log detail retrieved successfully"
                : $"Log with ID {id} not found");
        })
        .WithName("GetSerilogLogById")
        .WithTags("Serilogs");

        group.MapPost("/delete/{id:int}", async (int id, IMediator mediator) =>
        {
            var result = await mediator.Send(new DeleteSerilogLogsByIdCommand(id));

            if (!result)
            {
                return ((object?)null).ToApiResponse("Delete failed. The log data could not be found.");
            }

            return true.ToApiResponse("Log entry has been deleted successfully");
        })
        .WithName("DeleteSerilogLogById")
        .WithTags("Serilogs");

        group.MapPost("/clear-all", async (IMediator mediator) =>
        {
            await mediator.Send(new DeleteSerilogLogsAllCommand());

            return true.ToApiResponse("All database logs have been cleared successfully");
        })
        .WithName("DeleteSerilogLogsAll")
        .WithTags("Serilogs");
    }
}