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

namespace Indotalent.Features.Inventory.UnitMeasure;

public static class UnitMeasureEndpoint
{
    public static void MapUnitMeasureEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/unit-measure").WithTags("UnitMeasures")
            .RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser());

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

            return result.ToApiResponse("Unit measure list retrieved successfully");
        })
        .WithName("GetUnitMeasureList")
        .WithTags("UnitMeasures");

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

            return result.ToApiResponse(result is not null
                ? "Unit measure detail retrieved successfully"
                : $"Unit measure with ID {id} not found");
        })
        .WithName("GetUnitMeasureById")
        .WithTags("UnitMeasures");

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

            return result.ToApiResponse("Unit measure has been created successfully", StatusCodes.Status201Created);
        })
        .WithName("CreateUnitMeasure")
        .WithTags("UnitMeasures");

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

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

            return result.ToApiResponse("Unit measure has been updated successfully");
        })
        .WithName("UpdateUnitMeasure")
        .WithTags("UnitMeasures");

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

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

            return true.ToApiResponse("Unit measure has been deleted successfully");
        })
        .WithName("DeleteUnitMeasureById")
        .WithTags("UnitMeasures");
    }
}