using FastEndpoints;
using TaxBaik.Web.Services;

namespace TaxBaik.Web.Endpoints.Auth;

public class RefreshTokenRequest
{
    public string RefreshToken { get; set; } = string.Empty;
}

public class RefreshTokenEndpoint : Endpoint<RefreshTokenRequest, TokenPairResponse>
{
    private readonly AuthService _authService;

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

    public override void Configure()
    {
        Post("/api/auth/refresh");
        AllowAnonymous();
    }

    public override async Task HandleAsync(RefreshTokenRequest request, CancellationToken ct)
    {
        if (string.IsNullOrWhiteSpace(request.RefreshToken))
        {
            ThrowError("Refresh token이 필요합니다.");
        }

        var tokenPair = await _authService.RefreshAccessTokenAsync(request.RefreshToken);
        if (tokenPair == null)
        {
            ThrowError("Refresh token이 유효하지 않습니다.");
        }

        await SendAsync(new TokenPairResponse
        {
            Token = tokenPair!.AccessToken,
            AccessToken = tokenPair.AccessToken,
            RefreshToken = tokenPair.RefreshToken,
            ExpiresIn = tokenPair.ExpiresIn
        }, 200, cancellation: ct);
    }
}
