using NexusShell.Models;

namespace NexusShell.Services.Identity;

public sealed class NexusOrganizationService
{
    private NexusOrganizationRecord? _cached;

    public NexusOrganizationRecord? Load()
    {
        _cached = NexusIdentityStorage.Load<NexusOrganizationRecord>(NexusIdentityStorage.OrganizationPath);
        return _cached;
    }

    public NexusOrganizationRecord SaveFromCatalog(NexusOrganizationOption option)
    {
        var org = new NexusOrganizationRecord
        {
            Id = option.Id,
            Name = option.Name,
            CreatedAtUtc = DateTimeOffset.UtcNow,
        };

        NexusIdentityStorage.Save(NexusIdentityStorage.OrganizationPath, org);
        _cached = org;
        return org;
    }

    public NexusOrganizationRecord Save(string organizationName)
    {
        var org = new NexusOrganizationRecord
        {
            Id = $"ORG-{Guid.NewGuid().ToString("N")[..8].ToUpperInvariant()}",
            Name = organizationName.Trim(),
            CreatedAtUtc = DateTimeOffset.UtcNow,
        };

        NexusIdentityStorage.Save(NexusIdentityStorage.OrganizationPath, org);
        _cached = org;
        return org;
    }

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