import Flutter
import UIKit

public class ApplePayPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "apple_pay", binaryMessenger: registrar.messenger())
    let instance = ApplePayPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case "purchase":
        
        guard let args = call.arguments as? [String: Any],
              let appleId = args["appleId"] as? String,
              let appAccountToken = args["appAccountToken"] as? String else {
            result(["success": false, "error": "Invalid arguments"])
            return
        }
        
        ApplePayManager.shared.startPay(appleId: appleId, token: appAccountToken) { isSuccess, receipt in
            result([
                "success": isSuccess,
                "receipt": receipt ?? ""
            ])
        }
    case "restore":
        
        ApplePayManager.shared.restoreAction { isSuccess, receipt in
            result([
                "success": isSuccess,
                "receipt": receipt ?? ""
            ])
        }
    case "check":
        
        guard let args = call.arguments as? [String: Any],
              let appleId = args["appleId"] as? String else {
            result(false)
            return
        }
        
        if #available(iOS 15.0.0, *) {
            Task {
                let isEligible = await ApplePayManager.shared.check(appleId: appleId)
                DispatchQueue.main.async {
                   result(isEligible)
               }
            }
        } else {
            result(false)
        }
    case "getPlatformVersion":
      result("iOS " + UIDevice.current.systemVersion)
    default:
      result(FlutterMethodNotImplemented)
    }
  }
}
