using Indotalent.ConfigBackEnd.Extensions;
using Indotalent.Features.Pipeline.Budget.Cqrs;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;

namespace Indotalent.Features.Pipeline.Budget;

public static class BudgetEndpoint
{
    public static void MapBudgetEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/budget").WithTags("Budgets")
            .RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser());

        group.MapGet("/", async (IMediator mediator) =>
        {
            var result = await mediator.Send(new GetBudgetListQuery());
            return result.ToApiResponse("Budgets retrieved successfully");
        })
        .WithName("GetBudgetList");

        group.MapGet("/{id}", async (string id, IMediator mediator) =>
        {
            var result = await mediator.Send(new GetBudgetByIdQuery(id));
            return result.ToApiResponse(result is not null
                ? "Budget detail retrieved successfully"
                : $"Budget with ID {id} not found");
        })
        .WithName("GetBudgetById");

        group.MapPost("/", async (CreateBudgetRequest request, IMediator mediator) =>
        {
            var result = await mediator.Send(new CreateBudgetCommand(request));
            return result.ToApiResponse("Budget has been created successfully", StatusCodes.Status201Created);
        })
        .WithName("CreateBudget");

        group.MapPost("/update", async (UpdateBudgetRequest request, IMediator mediator) =>
        {
            var result = await mediator.Send(new UpdateBudgetCommand(request));
            if (!result.Success)
            {
                return ((object?)null).ToApiResponse("Update failed. The budget data could not be found.");
            }
            return result.ToApiResponse("Budget has been updated successfully");
        })
        .WithName("UpdateBudget");

        group.MapPost("/delete/{id}", async (string id, IMediator mediator) =>
        {
            var result = await mediator.Send(new DeleteBudgetByIdCommand(new DeleteBudgetByIdRequest(id)));
            if (!result)
            {
                return ((object?)null).ToApiResponse("Delete failed. The budget data could not be found.");
            }
            return true.ToApiResponse("Budget has been deleted successfully");
        })
        .WithName("DeleteBudgetById");

        group.MapGet("/lookup", async (IMediator mediator) =>
        {
            var result = await mediator.Send(new GetBudgetLookupQuery());
            return result.ToApiResponse("Budget lookup data retrieved successfully");
        })
        .WithName("GetBudgetLookup");
    }
}