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

namespace Indotalent.Features.Thirdparty.CustomerCategory;

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

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

            return result.ToApiResponse("Customer category list retrieved successfully");
        })
        .WithName("GetCustomerCategoryList")
        .WithTags("CustomerCategories");

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

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

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

            return result.ToApiResponse("Customer category has been created successfully", StatusCodes.Status201Created);
        })
        .WithName("CreateCustomerCategory")
        .WithTags("CustomerCategories");

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

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

            return result.ToApiResponse("Customer category has been updated successfully");
        })
        .WithName("UpdateCustomerCategory")
        .WithTags("CustomerCategories");

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

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

            return true.ToApiResponse("Customer category has been deleted successfully");
        })
        .WithName("DeleteCustomerCategoryById")
        .WithTags("CustomerCategories");
    }
}