using Indotalent.ConfigBackEnd.Extensions;
using Indotalent.Features.Thirdparty.CustomerGroup.Cqrs;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;

namespace Indotalent.Features.Thirdparty.CustomerGroup;

public static class CustomerGroupEndpoint
{
    public static void MapCustomerGroupEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/customer-group").WithTags("CustomerGroups")
            .RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser());

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

            return result.ToApiResponse("Customer group list retrieved successfully");
        })
        .WithName("GetCustomerGroupList")
        .WithTags("CustomerGroups");

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

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

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

            return result.ToApiResponse("Customer group has been created successfully", StatusCodes.Status201Created);
        })
        .WithName("CreateCustomerGroup")
        .WithTags("CustomerGroups");

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

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

            return result.ToApiResponse("Customer group has been updated successfully");
        })
        .WithName("UpdateCustomerGroup")
        .WithTags("CustomerGroups");

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

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

            return true.ToApiResponse("Customer group has been deleted successfully");
        })
        .WithName("DeleteCustomerGroupById")
        .WithTags("CustomerGroups");
    }
}