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

namespace Indotalent.Features.Pipeline.Lead;

public static class LeadEndpoint
{
    public static void MapLeadEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/lead").WithTags("Leads")
            .RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser());

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

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

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

        group.MapPost("/update", async (UpdateLeadRequest request, IMediator mediator) =>
        {
            var result = await mediator.Send(new UpdateLeadCommand(request));
            if (!result.Success)
            {
                return ((object?)null).ToApiResponse("Update failed. Lead not found.");
            }
            return result.ToApiResponse("Lead has been updated successfully");
        })
        .WithName("UpdateLead");

        group.MapPost("/delete/{id}", async (string id, IMediator mediator) =>
        {
            var result = await mediator.Send(new DeleteLeadByIdCommand(new DeleteLeadByIdRequest(id)));
            if (!result)
            {
                return ((object?)null).ToApiResponse("Delete failed. Lead not found.");
            }
            return true.ToApiResponse("Lead has been deleted successfully");
        })
        .WithName("DeleteLeadById");

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