using Microsoft.Extensions.Options;
using Nexus.Contracts.Devices;
using NexusIdentity.Api.Models;

namespace NexusIdentity.Api.Services;

public sealed class DevicePresenceOptions
{
    public const string SectionName = "Nexus:Presence";
    public int OfflineThresholdSeconds { get; set; } = 90;
}

public sealed class DevicePresenceService
{
    private readonly DevicePresenceOptions _options;

    public DevicePresenceService(IOptions<DevicePresenceOptions> options)
    {
        _options = options.Value;
    }

    public int OfflineThresholdSeconds => Math.Max(15, _options.OfflineThresholdSeconds);

    public bool IsOnline(DateTime? lastSeenUtc, DateTime utcNow)
    {
        if (lastSeenUtc is null)
        {
            return false;
        }

        return (utcNow - lastSeenUtc.Value).TotalSeconds <= OfflineThresholdSeconds;
    }

    public HealthStatus ResolveHealthStatus(string? lastHealth, bool online)
    {
        if (!online)
        {
            return HealthStatus.Offline;
        }

        return ParseHealthStatus(lastHealth);
    }

    public static HealthStatus ParseHealthStatus(string? health) =>
        health?.Trim() switch
        {
            "Critical" => HealthStatus.Critical,
            "Warning" => HealthStatus.Warning,
            "Offline" => HealthStatus.Offline,
            _ => HealthStatus.Healthy,
        };

    public static string ToHealthLabel(HealthStatus status) => status switch
    {
        HealthStatus.Critical => "Critical",
        HealthStatus.Warning => "Warning",
        HealthStatus.Offline => "Offline",
        _ => "Healthy",
    };
}
