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

namespace Indotalent.Features.Pipeline.LeadActivity;

public static class LeadActivityEndpoint
{
    public static void MapLeadActivityEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/lead-activity").WithTags("LeadActivities")
            .RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser());

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

        group.MapGet("/", async (IMediator mediator) =>
        {
            var result = await mediator.Send(new GetLeadActivityListQuery());
            return result.ToApiResponse("Lead activity list retrieved successfully");
        })
        .WithName("GetLeadActivityList");

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

        group.MapPost("/", async (CreateLeadActivityRequest request, IMediator mediator) =>
        {
            var result = await mediator.Send(new CreateLeadActivityCommand(request));
            return result.ToApiResponse("Lead activity has been created successfully", StatusCodes.Status201Created);
        })
        .WithName("CreateLeadActivity");

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

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