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

namespace Web.Api.Endpoints.MyPage;

internal sealed class ChangeThumb : IEndpoint
{
    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        app.MapPost("api/mypage/thumb", async (
            IFormFile? thumb,
            ClaimsPrincipal user,
            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.MyPage.ChangeThumb.Command(
                memberID.Value,
                thumb
            );

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

            return result.Match(
                data => ApiResponse.Ok(new { thumbUrl = data }),
                CustomResults.Problem
            );
        })
        .WithTags("MyPage")
        .RequireAuthorization()
        .DisableAntiforgery();
    }
}