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

namespace Indotalent.Features.Pipeline.Expense;

public static class ExpenseEndpoint
{
    public static void MapExpenseEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/expense").WithTags("Expenses")
            .RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser());

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

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

        group.MapPost("/", async (CreateExpenseRequest request, IMediator mediator) =>
        {
            var result = await mediator.Send(new CreateExpenseCommand(request));
            return result.ToApiResponse("Expense has been created successfully", StatusCodes.Status201Created);
        })
        .WithName("CreateExpense");

        group.MapPost("/update", async (UpdateExpenseRequest request, IMediator mediator) =>
        {
            var result = await mediator.Send(new UpdateExpenseCommand(request));
            if (!result.Success)
            {
                return ((object?)null).ToApiResponse("Update failed.");
            }
            return result.ToApiResponse("Expense has been updated successfully");
        })
        .WithName("UpdateExpense");

        group.MapPost("/delete/{id}", async (string id, IMediator mediator) =>
        {
            var result = await mediator.Send(new DeleteExpenseByIdCommand(new DeleteExpenseByIdRequest(id)));
            if (!result)
            {
                return ((object?)null).ToApiResponse("Delete failed.");
            }
            return true.ToApiResponse("Expense has been deleted successfully");
        })
        .WithName("DeleteExpenseById");

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