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

namespace Indotalent.Features.Setting.Company;

public static class CompanyEndpoint
{
    public static void MapCompanyEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/company").WithTags("Companies")
            .RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
            .RequireAuthenticatedUser());

        group.MapGet("/", async (IMediator mediator) =>
        {
            var result = await mediator.Send(new GetCompanyListQuery());
            return result.ToApiResponse("Company list retrieved successfully");
        });

        group.MapGet("/{id}", async (string id, IMediator mediator) =>
        {
            var result = await mediator.Send(new GetCompanyByIdQuery(id));
            return result.ToApiResponse(result is not null ? "Company retrieved" : "Not found");
        });

        group.MapPost("/", async (CreateCompanyRequest request, IMediator mediator) =>
        {
            var result = await mediator.Send(new CreateCompanyCommand(request));
            return result.ToApiResponse("Company created successfully", StatusCodes.Status201Created);
        });

        group.MapPost("/update", async (UpdateCompanyRequest request, IMediator mediator) =>
        {
            var result = await mediator.Send(new UpdateCompanyCommand(request));
            return result.Success ? result.ToApiResponse("Company updated") : result.ToApiResponse("Failed");
        });

        group.MapPost("/delete/{id}", async (string id, IMediator mediator) =>
        {
            var result = await mediator.Send(new DeleteCompanyByIdCommand(new DeleteCompanyByIdRequest(id)));
            return result.ToApiResponse("Company deleted");
        });
    }
}