using NexusShell.Agent.Models;
using NexusShell.Services;

namespace NexusShell.Agent;

/// <summary>
/// Aggregates device status for visibility: presence, health, versions.
/// </summary>
public sealed class NexusDeviceStatusService
{
    private readonly NexusPresenceService _presence;
    private readonly NexusHealthService _health;
    private readonly NexusAgentConfig _config;
    private readonly ClientVersionInfo _shellVersion;

    public NexusDeviceStatusService(
        NexusPresenceService presence,
        NexusHealthService health,
        NexusAgentConfig config,
        ClientVersionInfo shellVersion)
    {
        _presence = presence;
        _health = health;
        _config = config;
        _shellVersion = shellVersion;
    }

    public NexusAgentDeviceStatusSnapshot CaptureSnapshot()
    {
        var presence = _presence.CaptureSnapshot();
        var health = _health.CaptureSnapshot();

        return new NexusAgentDeviceStatusSnapshot
        {
            DeviceId = string.IsNullOrWhiteSpace(presence.DeviceId) ? _config.DeviceId : presence.DeviceId,
            User = presence.User,
            Organization = presence.Organization,
            Online = presence.Online,
            Health = health.Overall,
            HealthPercent = health.HealthPercent,
            AgentVersion = NexusAgentConfig.AgentVersion,
            ShellVersion = _shellVersion.Version,
            LastHeartbeatUtc = presence.LastHeartbeatUtc,
            LastSeenUtc = presence.LastHeartbeatUtc ?? DateTimeOffset.UtcNow,
            CapturedAtUtc = DateTimeOffset.UtcNow,
        };
    }
}

public sealed class NexusAgentDeviceStatusSnapshot
{
    public required string DeviceId { get; init; }
    public required string User { get; init; }
    public required string Organization { get; init; }
    public bool Online { get; init; }
    public required string Health { get; init; }
    public int HealthPercent { get; init; }
    public required string AgentVersion { get; init; }
    public required string ShellVersion { get; init; }
    public DateTimeOffset? LastHeartbeatUtc { get; init; }
    public DateTimeOffset LastSeenUtc { get; init; }
    public DateTimeOffset CapturedAtUtc { get; init; }
}
