using FastEndpoints;
using TaxBaik.Web.Services;

namespace TaxBaik.Web.Endpoints.Auth;

public class ResetPasswordRequest
{
    public string Username { get; set; } = string.Empty;
    public string NewPassword { get; set; } = string.Empty;
    public string ResetToken { get; set; } = string.Empty;
}

public class ResetPasswordEndpoint : Endpoint<ResetPasswordRequest, MessageResponse>
{
    private readonly AuthService _authService;

    public ResetPasswordEndpoint(AuthService authService)
    {
        _authService = authService;
    }

    public override void Configure()
    {
        Post("/api/auth/reset-password");
        AllowAnonymous();
    }

    public override async Task HandleAsync(ResetPasswordRequest request, CancellationToken ct)
    {
        try
        {
            var reset = await _authService.ResetPasswordAsync(request.Username, request.NewPassword, request.ResetToken);
            if (!reset)
            {
                ThrowError("재설정 토큰 또는 사용자 정보가 올바르지 않습니다.");
            }

            await SendAsync(new MessageResponse { Message = "비밀번호가 재설정되었습니다." }, 200, cancellation: ct);
        }
        catch (InvalidOperationException)
        {
            ThrowError("비밀번호 재설정 토큰이 서버에 설정되어 있지 않습니다.", statusCode: 503);
        }
        catch (ArgumentException ex)
        {
            ThrowError(ex.Message);
        }
    }
}
