using System.Security.Claims;
using Application.Abstractions.Messaging;
using Web.Api.Common;
using Web.Api.Extensions;

namespace Web.Api.Endpoints.Auth;

internal sealed class Logout : IEndpoint
{
    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        app.MapPost("api/auth/logout", async (
            ClaimsPrincipal user,
            ISender sender,
            HttpContext httpContext,
            CancellationToken ct
        ) => {
            var memberID = user.GetMemberID();

            if (memberID is null)
            {
                return ApiResponse.Fail(StatusCodes.Status401Unauthorized, "Invalid token");
            }

            var refreshToken = httpContext.Request.Cookies["refreshToken"];

            var command = new Application.Features.Api.Auth.Logout.Command(memberID.Value, refreshToken);

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

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