namespace ClaudeDo.Worker.Usage;

/// <summary>
/// Threadsafe holder for the last successful usage snapshot. A failed poll never overwrites
/// a good snapshot — it only records <see cref="LastError"/>, leaving the existing snapshot stale.
/// </summary>
public sealed class UsageState
{
    private readonly object _lock = new();
    private UsageSnapshot? _snapshot;
    private DateTime? _lastAttemptUtc;
    private string? _lastError;

    public UsageSnapshot? Snapshot
    {
        get { lock (_lock) return _snapshot; }
    }

    public DateTime? LastAttemptUtc
    {
        get { lock (_lock) return _lastAttemptUtc; }
    }

    public string? LastError
    {
        get { lock (_lock) return _lastError; }
    }

    public void ReportSuccess(UsageSnapshot snapshot)
    {
        lock (_lock)
        {
            _snapshot = snapshot;
            _lastAttemptUtc = snapshot.FetchedAtUtc;
            _lastError = null;
        }
    }

    public void ReportFailure(string error, DateTime attemptedAtUtc)
    {
        lock (_lock)
        {
            _lastAttemptUtc = attemptedAtUtc;
            _lastError = error;
        }
    }
}
