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

namespace Web.Api.Endpoints.Auth;

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

    public void MapEndpoint(IEndpointRouteBuilder app)
    {
        app.MapPost("api/auth/reset-password", async (
            Request request,
            HttpContext httpContext,
            ISender sender,
            CancellationToken ct
        ) =>
        {
            // 사전 비밀번호 재설정 검증 여부
            var cookieName = $"isVerified-ForgotPassword";
            var cookieValue = httpContext.Request.Cookies[cookieName] ?? string.Empty;

            var command = new Application.Features.Api.Auth.ResetPassword.Command(
                request.Email,
                request.Password,
                cookieValue
            );

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

            if (result.IsSuccess)
            {
                // 인증 쿠키 삭제
                httpContext.Response.Cookies.Delete(cookieName);
            }

            return result.Match(
                () => ApiResponse.Ok(new {
                    message = "비밀번호가 변경되었습니다." 
                }),
                CustomResults.Problem
            );
        })
        .WithTags("Auth")
        .AllowAnonymous();
    }
}