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

namespace Web.Api.Endpoints.Forum.Post;

internal sealed class ToggleBookmark : IEndpoint
{
    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        app.MapPost("api/forum/posts/{id}/bookmark", async (
            int id,
            ClaimsPrincipal user,
            HttpContext httpContext,
            ISender sender,
            CancellationToken ct
        ) => {
            var memberID = user.GetMemberID();
            if (memberID is null)
            {
                return ApiResponse.Fail(StatusCodes.Status401Unauthorized, "Invalid token");
            }

            var command = new Application.Features.Api.Forum.PostBookmark.Toggle.Command(
                memberID.Value,
                id,
                httpContext.Connection.RemoteIpAddress?.ToString(),
                httpContext.Request.Headers.UserAgent.ToString()
            );

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

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