using Indotalent.ConfigBackEnd.Extensions;
using Indotalent.Features.Inventory.ProductGroup.Cqrs;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;

namespace Indotalent.Features.Inventory.ProductGroup;

public static class ProductGroupEndpoint
{
    public static void MapProductGroupEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/product-group").WithTags("ProductGroups")
            .RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser());

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

            return result.ToApiResponse("Product group list retrieved successfully");
        })
        .WithName("GetProductGroupList")
        .WithTags("ProductGroups");

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

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

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

            return result.ToApiResponse("Product group has been created successfully", StatusCodes.Status201Created);
        })
        .WithName("CreateProductGroup")
        .WithTags("ProductGroups");

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

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

            return result.ToApiResponse("Product group has been updated successfully");
        })
        .WithName("UpdateProductGroup")
        .WithTags("ProductGroups");

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

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

            return true.ToApiResponse("Product group has been deleted successfully");
        })
        .WithName("DeleteProductGroupById")
        .WithTags("ProductGroups");
    }
}