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

namespace Indotalent.Features.Setting.Tax;

public static class TaxEndpoint
{
    public static void MapTaxEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/tax").WithTags("Taxes")
            .RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser());

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

            return result.ToApiResponse("Data tax retrieved successfully");
        })
        .WithName("GetTaxList")
        .WithTags("Taxes");

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

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

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

            return result.ToApiResponse("Tax has been created successfully", StatusCodes.Status201Created);
        })
        .WithName("CreateTax")
        .WithTags("Taxes");

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

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

            return result.ToApiResponse("Tax has been updated successfully");
        })
        .WithName("UpdateTax")
        .WithTags("Taxes");

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

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

            return true.ToApiResponse("Tax has been deleted successfully");
        })
        .WithName("DeleteTaxById")
        .WithTags("Taxes");
    }
}