namespace planli.frontend.Services;

/// <summary>
/// Silently renews the access-token by posting to /api/Auth/refresh.
/// The refresh-token HttpOnly cookie is attached automatically by the browser.
/// A SemaphoreSlim prevents concurrent refresh storms.
/// </summary>
public sealed class RefreshService : IDisposable
{
    private readonly HttpClient    _plain;   // CookieHandler only — no retry logic
    private readonly SemaphoreSlim _lock = new(1, 1);

    public RefreshService(HttpClient plain) => _plain = plain;

    /// <summary>
    /// Posts to /api/Auth/refresh (no body — token comes from the cookie).
    /// Returns true when the server issued fresh cookies.
    /// </summary>
    public async Task<bool> TryRefreshAsync()
    {
        await _lock.WaitAsync();
        try
        {
            var res = await _plain.PostAsync("api/Auth/refresh", null);
            return res.IsSuccessStatusCode;
        }
        catch { return false; }
        finally { _lock.Release(); }
    }

    public void Dispose() => _lock.Dispose();
}
