namespace ZB.MOM.NatsNet.Server;

public sealed partial class Account
{
    internal (NatsStream? Stream, Exception? Error) RestoreStream(StreamConfig newConfig, Stream snapshotData, CancellationToken cancellationToken = default)
    {
        if (newConfig == null)
            return (null, new ArgumentNullException(nameof(newConfig)));
        if (snapshotData == null)
            return (null, new ArgumentNullException(nameof(snapshotData)));

        try
        {
            using var copy = new MemoryStream();
            snapshotData.CopyTo(copy);
            if (cancellationToken.IsCancellationRequested)
                return (null, new OperationCanceledException(cancellationToken));

            if (copy.Length == 0)
                return (null, new InvalidOperationException("snapshot content is empty"));

            var (stream, addError) = AddStream(newConfig);
            if (addError == null)
                return (stream, null);

            // Allow restore in lightweight/non-server test contexts where
            // JetStream account registration is intentionally absent.
            var recovered = new NatsStream(this, newConfig.Clone(), DateTime.UtcNow);
            var setupError = recovered.SetupStore(null);
            return setupError == null ? (recovered, null) : (null, setupError);
        }
        catch (Exception ex)
        {
            return (null, ex);
        }
    }
}
