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

namespace Indotalent.Features.Inventory.Warehouse;

public static class WarehouseEndpoint
{
    public static void MapWarehouseEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/warehouse").WithTags("Warehouses")
            .RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser());

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

            return result.ToApiResponse("Warehouse list retrieved successfully");
        })
        .WithName("GetWarehouseList")
        .WithTags("Warehouses");

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

            return result.ToApiResponse(result is not null
                ? "Warehouse detail retrieved successfully"
                : $"Warehouse with ID {id} not found");
        })
        .WithName("GetWarehouseById")
        .WithTags("Warehouses");

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

            return result.ToApiResponse("Warehouse has been created successfully", StatusCodes.Status201Created);
        })
        .WithName("CreateWarehouse")
        .WithTags("Warehouses");

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

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

            return result.ToApiResponse("Warehouse has been updated successfully");
        })
        .WithName("UpdateWarehouse")
        .WithTags("Warehouses");

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

            if (!result)
            {
                return ((object?)null).ToApiResponse("Delete failed. The warehouse might be a system warehouse or not found.");
            }

            return true.ToApiResponse("Warehouse has been deleted successfully");
        })
        .WithName("DeleteWarehouseById")
        .WithTags("Warehouses");
    }
}