import 'package:flutter_poolakey/flutter_poolakey.dart';

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

/// پرداختِ درون‌برنامه‌ایِ کافه‌بازار (Poolakey) — flavorِ `bazaar`.
class BazaarPaymentGateway implements PaymentGateway {
  bool _connected = false;

  @override
  String get store => 'bazaar';

  @override
  Future<void> connect() async {
    if (_connected) return;
    await FlutterPoolakey.connect(
      AppConfig.bazaarRsaKey,
      onDisconnected: () => _connected = false,
    );
    _connected = true;
  }

  @override
  Future<PurchaseResult> purchase(String productSku, {String payload = ''}) async {
    try {
      await connect();
      final info = await FlutterPoolakey.purchase(
        productSku,
        payload: payload.isNotEmpty ? payload : 'hakemsho',
      );
      if (info.purchaseToken.isEmpty) {
        return const PurchaseResult.failure();
      }
      return PurchaseResult.success(
        token: info.purchaseToken,
        purchaseData: info.originalJson,
        signature: info.dataSignature,
        // کالای مصرفی باید مصرف شود تا خریدِ مجدد ممکن باشد.
        onConfirmed: () => FlutterPoolakey.consume(info.purchaseToken),
      );
    } catch (_) {
      // کنسل‌شدن یا خطای بازار ⇒ شکستِ خرید.
      return const PurchaseResult.failure();
    }
  }
}
