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

namespace Indotalent.Features.Thirdparty.VendorCategory;

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

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

            return result.ToApiResponse("Vendor category list retrieved successfully");
        })
        .WithName("GetVendorCategoryList")
        .WithTags("VendorCategories");

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

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

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

            return result.ToApiResponse("Vendor category has been created successfully", StatusCodes.Status201Created);
        })
        .WithName("CreateVendorCategory")
        .WithTags("VendorCategories");

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

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

            return result.ToApiResponse("Vendor category has been updated successfully");
        })
        .WithName("UpdateVendorCategory")
        .WithTags("VendorCategories");

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

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

            return true.ToApiResponse("Vendor category has been deleted successfully");
        })
        .WithName("DeleteVendorCategoryById")
        .WithTags("VendorCategories");
    }
}