using NexusShell.Models;

namespace NexusShell.Services.Identity;

public sealed class NexusUserProfileService
{
    private NexusUserRecord? _cached;

    public NexusUserRecord? Load()
    {
        _cached = NexusIdentityStorage.Load<NexusUserRecord>(NexusIdentityStorage.UserPath);
        return _cached;
    }

    public NexusUserRecord Save(string displayName, NexusOrganizationRecord organization)
    {
        var user = new NexusUserRecord
        {
            Id = $"USR-{Guid.NewGuid().ToString("N")[..8].ToUpperInvariant()}",
            DisplayName = displayName.Trim(),
            OrganizationId = organization.Id,
            OrganizationName = organization.Name,
            CreatedAtUtc = DateTimeOffset.UtcNow,
        };

        NexusIdentityStorage.Save(NexusIdentityStorage.UserPath, user);
        _cached = user;
        return user;
    }

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