using System.Security.Claims;
using MediatR;
using SharedKernel.Extensions;
using Web.Api.Common;
using Web.Api.Extensions;

namespace Web.Api.Endpoints.MyPage;

internal sealed class ChangeEmail : IEndpoint
{
    public sealed record Request(string NewEmail);

    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        app.MapPost("api/mypage/email", async (
            Request request,
            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.MyPage.ChangeEmail.Command(
                memberID.Value,
                request.NewEmail,
                httpContext.GetClientIP(),
                httpContext.GetUserAgent(),
                httpContext.GetReferer()
            );

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

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