import ComposableArchitecture
import Utilities

/// Only allows for many-to-one producer -> consumer behaviors, and originally intended to be consumed by
/// `RootCoordinatorV1`.
/// Note that if `RootCoordinatorV1` is establishing a stream with this dependency, establishing another
/// stream will overwrite `RootCoordinatorV1`'s ownership.
/// For context see https://github.com/suno-ai/app-ios/pull/802
public struct ClipListItemDelegateClient {
    public var send: (_ action: ClipListItem.Action.DelegateClient) -> Void
    public var getStream: () -> AsyncStream<ClipListItem.Action.DelegateClient>
}

extension ClipListItemDelegateClient: DependencyKey {
    public static var liveValue: ClipListItemDelegateClient {
        var continuation: AsyncStream<ClipListItem.Action.DelegateClient>.Continuation?

        return Self(
            send: { action in
                continuation?.yield(action)
            },
            getStream: {
                var delegateAction: AsyncStream<ClipListItem.Action.DelegateClient>
                continuation?.finish()
                (delegateAction, continuation) = AsyncStream.makeStream()
                return delegateAction
            }
        )
    }
}
