import Flutter
import UIKit
import receive_sharing_intent

// FlutterSceneDelegate has a fallback that forwards URL events to plugins
// registered via addApplicationDelegate, but the fallback is best-effort and
// has not always fired in our setup. This subclass forwards URLs explicitly
// to receive_sharing_intent so cold-start and warm shares both reach Dart.
class SceneDelegate: FlutterSceneDelegate {
  override func scene(
    _ scene: UIScene,
    willConnectTo session: UISceneSession,
    options connectionOptions: UIScene.ConnectionOptions
  ) {
    super.scene(scene, willConnectTo: session, options: connectionOptions)
    for context in connectionOptions.urlContexts {
      _ = ReceiveSharingIntentPlugin.instance.application(
        UIApplication.shared,
        didFinishLaunchingWithOptions: [UIApplication.LaunchOptionsKey.url: context.url]
      )
    }
  }

  override func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    for context in URLContexts {
      _ = ReceiveSharingIntentPlugin.instance.application(
        UIApplication.shared,
        open: context.url,
        options: [:]
      )
    }
  }
}
