using ZB.MOM.NatsNet.Server.Internal.DataStructures;

namespace ZB.MOM.NatsNet.Server;

internal sealed partial class JsAccount
{
    internal bool SubjectsOverlap(string[] subjects, StreamAssignment? ownAssignment)
    {
        Lock.EnterReadLock();
        try
        {
            foreach (var stream in Streams.Values.OfType<NatsStream>())
            {
                if (ownAssignment != null && ReferenceEquals(stream.StreamAssignment(), ownAssignment))
                    continue;

                foreach (var left in subjects)
                {
                    foreach (var right in stream.Config.Subjects ?? [])
                    {
                        if (SubscriptionIndex.SubjectsCollide(left, right))
                            return true;
                    }
                }
            }

            return false;
        }
        finally
        {
            Lock.ExitReadLock();
        }
    }

    internal Exception? ConfigUpdateCheck(StreamConfig current, StreamConfig proposed)
    {
        if (!string.Equals(current.Name, proposed.Name, StringComparison.Ordinal))
            return new InvalidOperationException("stream name may not change");

        if (current.Storage != proposed.Storage)
            return new InvalidOperationException("stream storage may not change");

        return null;
    }
}
