using NexusShell.Models;

namespace NexusShell.Services.Identity;

public sealed class NexusDeviceTrustService
{
    private NexusTrustRecord? _cached;

    public NexusTrustRecord? Load()
    {
        _cached = NexusIdentityStorage.Load<NexusTrustRecord>(NexusIdentityStorage.TrustPath);
        return _cached;
    }

    public NexusTrustRecord InitializeForDevice(string deviceId)
    {
        var trust = new NexusTrustRecord
        {
            DeviceId = deviceId,
            Status = NexusTrustStatus.Pending,
            EvaluatedAtUtc = DateTimeOffset.UtcNow,
            Reason = "Lokal enrollment — afventer godkendelse",
        };

        NexusIdentityStorage.Save(NexusIdentityStorage.TrustPath, trust);
        _cached = trust;
        return trust;
    }

    public NexusTrustRecord UpdateStatus(NexusTrustStatus status, string? reason = null)
    {
        var current = Current ?? new NexusTrustRecord();
        var trust = new NexusTrustRecord
        {
            DeviceId = current.DeviceId,
            Status = status,
            EvaluatedAtUtc = DateTimeOffset.UtcNow,
            Reason = reason ?? current.Reason,
        };

        NexusIdentityStorage.Save(NexusIdentityStorage.TrustPath, trust);
        _cached = trust;
        return trust;
    }

    public void TouchLastSeen(NexusDeviceRecord device)
    {
        device.LastSeen = DateTimeOffset.UtcNow;
        NexusIdentityStorage.Save(NexusIdentityStorage.DevicePath, device);
    }

    public NexusTrustRecord? Current => _cached ?? Load();
}
