using System.Security.Claims;
using FastEndpoints;
using TaxBaik.Web.Services;

namespace TaxBaik.Web.Endpoints.Auth;

public class ChangePasswordRequest
{
    public string CurrentPassword { get; set; } = string.Empty;
    public string NewPassword { get; set; } = string.Empty;
}

public class MessageResponse
{
    public string Message { get; set; } = string.Empty;
}

public class ChangePasswordEndpoint : Endpoint<ChangePasswordRequest, MessageResponse>
{
    private readonly AuthService _authService;

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

    public override void Configure()
    {
        Post("/api/auth/change-password");
        Policies("Bearer");
    }

    public override async Task HandleAsync(ChangePasswordRequest request, CancellationToken ct)
    {
        var username = User.FindFirstValue(ClaimTypes.Name);
        if (string.IsNullOrWhiteSpace(username))
        {
            ThrowError("인증 정보가 올바르지 않습니다.");
        }

        try
        {
            var changed = await _authService.ChangePasswordAsync(username!, request.CurrentPassword, request.NewPassword);
            if (!changed)
            {
                ThrowError("현재 비밀번호가 올바르지 않습니다.");
            }

            await SendAsync(new MessageResponse { Message = "비밀번호가 변경되었습니다." }, 200, cancellation: ct);
        }
        catch (ArgumentException ex)
        {
            ThrowError(ex.Message);
        }
    }
}
