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

namespace Indotalent.Features.Thirdparty.VendorGroup;

public static class VendorGroupEndpoint
{
    public static void MapVendorGroupEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/vendor-group").WithTags("VendorGroups")
            .RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser());

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

            return result.ToApiResponse("Vendor group list retrieved successfully");
        })
        .WithName("GetVendorGroupList")
        .WithTags("VendorGroups");

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

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

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

            return result.ToApiResponse("Vendor group has been created successfully", StatusCodes.Status201Created);
        })
        .WithName("CreateVendorGroup")
        .WithTags("VendorGroups");

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

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

            return result.ToApiResponse("Vendor group has been updated successfully");
        })
        .WithName("UpdateVendorGroup")
        .WithTags("VendorGroups");

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

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

            return true.ToApiResponse("Vendor group has been deleted successfully");
        })
        .WithName("DeleteVendorGroupById")
        .WithTags("VendorGroups");
    }
}