import 'package:myket_iap/myket_iap.dart';
import 'package:myket_iap/util/purchase.dart';

import '../config.dart';
import 'payment_gateway.dart';

/// پرداختِ درون‌برنامه‌ایِ مایکت (flavorِ `myket`).
class MyketPaymentGateway implements PaymentGateway {
  bool _inited = false;

  @override
  String get store => 'myket';

  @override
  Future<void> connect() async {
    if (_inited) return;
    await MyketIAP.init(rsaKey: AppConfig.myketRsaKey, enableDebugLogging: false);
    _inited = true;
  }

  @override
  Future<PurchaseResult> purchase(String productSku, {String payload = ''}) async {
    await connect();
    final Map<dynamic, dynamic> result = await MyketIAP.launchPurchaseFlow(
      sku: productSku,
      payload: payload.isNotEmpty ? payload : 'hakemsho',
    );

    final Purchase? purchase = result[MyketIAP.PURCHASE] as Purchase?;
    if (purchase == null || purchase.mToken.isEmpty) {
      return const PurchaseResult.failure();
    }

    return PurchaseResult.success(
      token: purchase.mToken,
      purchaseData: purchase.mOriginalJson,
      signature: purchase.mSignature,
      // کالای مصرفی (سکه/بلیت) باید مصرف شود تا کاربر بتواند دوباره بخرد.
      onConfirmed: () => MyketIAP.consume(purchase: purchase),
    );
  }
}
