using System;

namespace StellaOps.Scanner.WebService.Diagnostics;

/// <summary>
/// Tracks runtime health snapshots for the Scanner WebService.
/// </summary>
public sealed class ServiceStatus
{
    private readonly TimeProvider timeProvider;
    private readonly DateTimeOffset startedAt;
    private ReadySnapshot readySnapshot;

    public ServiceStatus(TimeProvider timeProvider)
    {
        this.timeProvider = timeProvider ?? throw new ArgumentNullException(nameof(timeProvider));
        startedAt = timeProvider.GetUtcNow();
        readySnapshot = ReadySnapshot.CreateInitial(startedAt);
    }

    public ServiceSnapshot CreateSnapshot()
    {
        var now = timeProvider.GetUtcNow();
        return new ServiceSnapshot(startedAt, now, readySnapshot);
    }

    public void RecordReadyCheck(bool success, TimeSpan latency, string? error)
    {
        var now = timeProvider.GetUtcNow();
        readySnapshot = new ReadySnapshot(now, latency, success, success ? null : error);
    }

    public readonly record struct ServiceSnapshot(
        DateTimeOffset StartedAt,
        DateTimeOffset CapturedAt,
        ReadySnapshot Ready);

    public readonly record struct ReadySnapshot(
        DateTimeOffset CheckedAt,
        TimeSpan? Latency,
        bool IsReady,
        string? Error)
    {
        public static ReadySnapshot CreateInitial(DateTimeOffset timestamp)
            => new ReadySnapshot(timestamp, null, true, null);
    }
}
