using Indotalent.ConfigBackEnd.Extensions;
using Indotalent.Features.Setting.Currency.Cqrs;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;

namespace Indotalent.Features.Setting.Currency;

public static class CurrencyEndpoint
{
    public static void MapCurrencyEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/currency").WithTags("Currencies")
            .RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser());

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

            return result.ToApiResponse("Data currency retrieved successfully");
        })
        .WithName("GetCurrencyList")
        .WithTags("Currencies");

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

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

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

            return result.ToApiResponse("Currency has been created successfully", StatusCodes.Status201Created);
        })
        .WithName("CreateCurrency")
        .WithTags("Currencies");

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

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

            return result.ToApiResponse("Currency has been updated successfully");
        })
        .WithName("UpdateCurrency")
        .WithTags("Currencies");

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

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

            return true.ToApiResponse("Currency has been deleted successfully");
        })
        .WithName("DeleteCurrencyById")
        .WithTags("Currencies");
    }
}