using NexusShell.Services.Identity;

namespace NexusShell.Agent;

/// <summary>
/// Tracks local device presence for Control Center visibility (no remote control).
/// </summary>
public sealed class NexusPresenceService
{
    private readonly NexusIdentityService? _identity;
    private readonly object _gate = new();
    private DateTimeOffset? _lastHeartbeatUtc;
    private bool _online = true;

    public NexusPresenceService(NexusIdentityService? identity = null)
    {
        _identity = identity;
    }

    public DateTimeOffset? LastHeartbeatUtc
    {
        get { lock (_gate) return _lastHeartbeatUtc; }
    }

    public bool IsOnline
    {
        get { lock (_gate) return _online; }
    }

    public NexusAgentPresenceSnapshot CaptureSnapshot()
    {
        var identity = _identity?.GetSnapshot();
        var device = identity?.Device;
        var user = identity?.User;
        var org = identity?.Organization;

        lock (_gate)
        {
            return new NexusAgentPresenceSnapshot
            {
                DeviceId = device?.DeviceId ?? string.Empty,
                User = user?.DisplayName ?? device?.Owner ?? "—",
                Organization = org?.Name ?? device?.Organization ?? "—",
                Online = _online,
                LastHeartbeatUtc = _lastHeartbeatUtc ?? device?.LastSeen,
                CapturedAtUtc = DateTimeOffset.UtcNow,
            };
        }
    }

    public void RecordHeartbeat(DateTimeOffset timestamp, bool online = true)
    {
        lock (_gate)
        {
            _lastHeartbeatUtc = timestamp;
            _online = online;
        }
    }

    public void SetOffline()
    {
        lock (_gate)
        {
            _online = false;
        }
    }
}

public sealed class NexusAgentPresenceSnapshot
{
    public required string DeviceId { get; init; }
    public required string User { get; init; }
    public required string Organization { get; init; }
    public bool Online { get; init; }
    public DateTimeOffset? LastHeartbeatUtc { get; init; }
    public DateTimeOffset CapturedAtUtc { get; init; }
}
