using Indotalent.ConfigBackEnd.Extensions;
using Indotalent.Features.Setting.AutoNumberSequence.Cqrs;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;

namespace Indotalent.Features.Setting.AutoNumberSequence;

public static class AutoNumberSequenceEndpoint
{
    public static void MapAutoNumberSequenceEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/auto-number-sequences").WithTags("Auto Number Sequences")
            .RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser());

        group.MapGet("/", async (IMediator mediator) =>
        {
            var result = await mediator.Send(new GetAutoNumberSequenceListQuery());
            return result.ToApiResponse("Data auto number sequences retrieved successfully");
        })
        .WithName("GetAutoNumberSequenceList")
        .WithTags("Auto Number Sequences");

        group.MapGet("/{id}", async (string id, IMediator mediator) =>
        {
            var result = await mediator.Send(new GetAutoNumberSequenceByIdQuery(id));
            return result.ToApiResponse(result is not null
                ? "Sequence detail retrieved successfully"
                : $"Sequence with ID {id} not found");
        })
        .WithName("GetAutoNumberSequenceById")
        .WithTags("Auto Number Sequences");

        group.MapPost("/update", async (UpdateAutoNumberSequenceRequest request, IMediator mediator) =>
        {
            var result = await mediator.Send(new UpdateAutoNumberSequenceCommand(request));

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

            return result.ToApiResponse("Sequence has been updated successfully");
        })
        .WithName("UpdateAutoNumberSequence")
        .WithTags("Auto Number Sequences");
    }
}