/// Stripe payment stub — author/dev unlock without a live key.
/// © 2026 Jason Li. All rights reserved.
class PaymentStatus {
  static const succeeded = 'succeeded';
  static const failed = 'failed';
  static const cancelled = 'cancelled';
}

class PaymentResult {
  final String status;
  final String message;
  const PaymentResult({required this.status, required this.message});
}

class StripeService {
  /// Publishable key from `--dart-define=STRIPE_PK=...`.
  /// Empty / placeholder → development mode (auto-succeed).
  static const String publishableKey = String.fromEnvironment(
    'STRIPE_PK',
    defaultValue: '',
  );

  static bool get isDevMode {
    final key = publishableKey.trim();
    return key.isEmpty ||
        key.startsWith('pk_test') ||
        key.contains('placeholder');
  }

  static Future<PaymentResult> purchaseReport({
    required String productId,
    required double amountUsd,
  }) async {
    await Future<void>.delayed(const Duration(milliseconds: 600));

    // Author session unlocks reports without Stripe.
    if (AuthorAccess.isUnlocked) {
      return const PaymentResult(
        status: PaymentStatus.succeeded,
        message: 'Author unlock · 作者权限已解锁',
      );
    }

    if (isDevMode) {
      return PaymentResult(
        status: PaymentStatus.succeeded,
        message:
            'Dev unlock · report $productId (\$${amountUsd.toStringAsFixed(2)})',
      );
    }

    // Live key present but no Payment Sheet wired yet.
    return const PaymentResult(
      status: PaymentStatus.failed,
      message: 'Stripe Payment Sheet not configured for this build.',
    );
  }
}

/// Author privilege unlocked via `?unlock=master` (web) or dart-define.
class AuthorAccess {
  static bool _unlocked = false;

  static bool get isUnlocked => _unlocked;

  static void unlock() => _unlocked = true;

  /// Call once at startup. Honors URL `?unlock=master` and `--dart-define=UNLOCK=master`.
  static void applyFromLaunch({Uri? uri, String unlockDefine = ''}) {
    final define = unlockDefine.trim().isEmpty
        ? const String.fromEnvironment('UNLOCK', defaultValue: '')
        : unlockDefine.trim();
    if (define == 'master') {
      _unlocked = true;
      return;
    }
    final u = uri;
    if (u != null && u.queryParameters['unlock'] == 'master') {
      _unlocked = true;
    }
  }
}
