using Indotalent.ConfigBackEnd.Extensions;
using Indotalent.Features.Utilities.BookingGroup.Cqrs;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;

namespace Indotalent.Features.Utilities.BookingGroup;

public static class BookingGroupEndpoint
{
    public static void MapBookingGroupEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/booking-group").WithTags("BookingGroups")
            .RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser());

        group.MapGet("/", async (IMediator mediator) =>
        {
            var result = await mediator.Send(new GetBookingGroupListQuery());

            return result.ToApiResponse("Booking group list retrieved successfully");
        })
        .WithName("GetBookingGroupList")
        .WithTags("BookingGroups");

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

            return result.ToApiResponse(result is not null
                ? "Booking group detail retrieved successfully"
                : $"Booking group with ID {id} not found");
        })
        .WithName("GetBookingGroupById")
        .WithTags("BookingGroups");

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

            return result.ToApiResponse("Booking group has been created successfully", StatusCodes.Status201Created);
        })
        .WithName("CreateBookingGroup")
        .WithTags("BookingGroups");

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

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

            return result.ToApiResponse("Booking group has been updated successfully");
        })
        .WithName("UpdateBookingGroup")
        .WithTags("BookingGroups");

        group.MapPost("/delete/{id}", async (string id, IMediator mediator) =>
        {
            var result = await mediator.Send(new DeleteBookingGroupByIdCommand(new DeleteBookingGroupByIdRequest(id)));

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

            return true.ToApiResponse("Booking group has been deleted successfully");
        })
        .WithName("DeleteBookingGroupById")
        .WithTags("BookingGroups");
    }
}