using SharedKernel.Extensions;
using Application.Abstractions.Messaging;
using Web.Api.Extensions;
using Web.Api.Common;

namespace Web.Api.Endpoints.Auth;

internal sealed class Login : IEndpoint
{
    public sealed record Request(
        string Email,
        string Password
    );

    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        app.MapPost("api/auth/login", async (
            Request request,
            HttpContext httpContext,
            ISender sender,
            CancellationToken ct
        ) => {

            var ipAddress = httpContext.GetClientIP();
            var userAgent = httpContext.GetUserAgent();

            var command = new Application.Features.Api.Auth.Login.Command(
                request.Email,
                request.Password,
                ipAddress,
                userAgent
            );

            var result = await sender.Send(command, ct);

            return result.Match(
                data => ApiResponse.Ok(data),
                CustomResults.Problem
            );
        })
        .WithTags("Auth")
        .AllowAnonymous();
    }
}