/// 会员状态与解锁 — © 2026 Jason Li
library;

import 'package:shared_preferences/shared_preferences.dart';

import '../services/stripe_service.dart';
import 'author_access.dart';
import 'billing_sku.dart';
import 'tiers.dart';

class MembershipStore {
  static const _tierKey = 'kr_product_tier';
  static const _subExpiresKey = 'kr_sub_expires_ms';
  static const _singleJudgmentExpiresKey = 'kr_single_judgment_expires_ms';

  static Future<ProductTier> currentTier() async {
    // 作者 PIN 会话期间视为键共振最高档（全部页面）
    if (await AuthorAccess.isUnlocked()) {
      return ProductTier.resonanceMaster;
    }
    if (await _subscriptionActive()) {
      return ProductTier.resonanceMaster;
    }
    final prefs = await SharedPreferences.getInstance();
    final raw = prefs.getString(_tierKey);
    return ProductTier.values.firstWhere(
      (e) => e.name == raw,
      orElse: () => ProductTier.free,
    );
  }

  /// 持久购买档（不含作者会话 / 订阅覆盖）
  static Future<ProductTier> purchasedTier() async {
    final prefs = await SharedPreferences.getInstance();
    final raw = prefs.getString(_tierKey);
    return ProductTier.values.firstWhere(
      (e) => e.name == raw,
      orElse: () => ProductTier.free,
    );
  }

  static Future<void> setTier(ProductTier tier) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_tierKey, tier.name);
  }

  static Future<bool> _subscriptionActive() async {
    final prefs = await SharedPreferences.getInstance();
    final ms = prefs.getInt(_subExpiresKey);
    if (ms == null) return false;
    if (DateTime.now().millisecondsSinceEpoch >= ms) {
      await prefs.remove(_subExpiresKey);
      return false;
    }
    return true;
  }

  static Future<DateTime?> subscriptionExpiresAt() async {
    final prefs = await SharedPreferences.getInstance();
    final ms = prefs.getInt(_subExpiresKey);
    if (ms == null) return null;
    if (DateTime.now().millisecondsSinceEpoch >= ms) {
      await prefs.remove(_subExpiresKey);
      return null;
    }
    return DateTime.fromMillisecondsSinceEpoch(ms);
  }

  static Future<void> activateSubscription({
    required Duration period,
  }) async {
    final prefs = await SharedPreferences.getInstance();
    final until = DateTime.now().add(period);
    await prefs.setInt(_subExpiresKey, until.millisecondsSinceEpoch);
  }

  static Future<bool> singleJudgmentActive() async {
    final prefs = await SharedPreferences.getInstance();
    final ms = prefs.getInt(_singleJudgmentExpiresKey);
    if (ms == null) return false;
    if (DateTime.now().millisecondsSinceEpoch >= ms) {
      await prefs.remove(_singleJudgmentExpiresKey);
      return false;
    }
    return true;
  }

  static Future<DateTime?> singleJudgmentExpiresAt() async {
    final prefs = await SharedPreferences.getInstance();
    final ms = prefs.getInt(_singleJudgmentExpiresKey);
    if (ms == null) return null;
    if (DateTime.now().millisecondsSinceEpoch >= ms) {
      await prefs.remove(_singleJudgmentExpiresKey);
      return null;
    }
    return DateTime.fromMillisecondsSinceEpoch(ms);
  }

  static Future<void> activateSingleJudgment({
    Duration period = const Duration(hours: 24),
  }) async {
    final prefs = await SharedPreferences.getInstance();
    final until = DateTime.now().add(period);
    await prefs.setInt(
      _singleJudgmentExpiresKey,
      until.millisecondsSinceEpoch,
    );
  }

  static Future<StripePayResult> purchase(ProductTier tier) async {
    final sku = switch (tier) {
      ProductTier.pro => BillingSku.proLifetime,
      ProductTier.resonanceMaster => BillingSku.masterLifetime,
      ProductTier.free => null,
    };
    if (sku == null) {
      return const StripePayResult(
        ok: true,
        mode: 'free',
        message: '免费档无需购买',
      );
    }
    return purchaseSku(sku);
  }

  /// 按 [BillingSku] 购买（买断 / 订阅 / 单次）
  static Future<StripePayResult> purchaseSku(BillingSku sku) async {
    final owned = await purchasedTier();

    if (sku == BillingSku.proLifetime &&
        (owned == ProductTier.pro || owned == ProductTier.resonanceMaster)) {
      return StripePayResult(
        ok: true,
        mode: 'owned',
        message: '已解锁：${ProductTier.pro.zh}',
      );
    }
    if (sku == BillingSku.masterLifetime &&
        owned == ProductTier.resonanceMaster) {
      return StripePayResult(
        ok: true,
        mode: 'owned',
        message: '已解锁：${ProductTier.resonanceMaster.zh}',
      );
    }

    final result = await StripeService.purchaseSku(sku, ownedTier: owned);
    if (!result.ok) return result;

    if (sku.isSinglePass) {
      await activateSingleJudgment();
      return StripePayResult(
        ok: true,
        mode: result.mode,
        message: '单次判局通行证已激活（24 小时）',
        checkoutUrl: result.checkoutUrl,
        sessionId: result.sessionId,
      );
    }
    if (sku.isSubscription) {
      final period = sku == BillingSku.masterMonthly
          ? const Duration(days: 31)
          : const Duration(days: 366);
      await activateSubscription(period: period);
      return StripePayResult(
        ok: true,
        mode: result.mode,
        message: '键共振订阅已激活',
        checkoutUrl: result.checkoutUrl,
        sessionId: result.sessionId,
      );
    }

    final target = sku.grantsTier;
    if (target.index > owned.index) {
      await setTier(target);
    }
    return result;
  }

  /// 用 Stripe Checkout session_id 向服务器确认付款并持久解锁。
  static Future<StripePayResult> unlockFromCheckoutSession(
    String sessionId,
  ) async {
    final verified = await StripeService.verifyCheckoutSession(sessionId);
    if (verified == null) {
      return const StripePayResult(
        ok: false,
        mode: 'verify_failed',
        message: '未能确认付款，请稍后在会员页重试或联系支持。',
      );
    }

    String message;
    if (verified.entitlement == 'singleJudgment' ||
        verified.sku == BillingSku.singleJudgment) {
      await activateSingleJudgment();
      message = '已确认付款：单次判局通行证（24 小时）';
    } else if (verified.entitlement == 'subscription' ||
        verified.sku?.isSubscription == true) {
      final days = verified.periodDays ??
          (verified.sku == BillingSku.masterYearly ? 366 : 31);
      await activateSubscription(period: Duration(days: days));
      message = '已确认付款：键共振订阅（$days 天）';
    } else {
      final current = await purchasedTier();
      if (verified.tier.index > current.index) {
        await setTier(verified.tier);
      }
      message = '已确认付款并解锁：${verified.tier.zh}';
    }

    await StripeService.savePendingSession(null);
    return StripePayResult(
      ok: true,
      mode: 'verified',
      message: message,
      sessionId: sessionId,
    );
  }

  /// App 回到时：若有未完成的 session，自动向 Stripe 校验一次。
  static Future<StripePayResult?> syncPendingCheckout() async {
    final pending = await StripeService.pendingSessionId();
    if (pending == null || pending.isEmpty) return null;
    return unlockFromCheckoutSession(pending);
  }

  /// 兼容旧调用
  static Future<bool> unlockDemo(ProductTier tier) async {
    final r = await purchase(tier);
    return r.ok;
  }

  static Future<bool> has(AppFeature feature) async {
    final tier = await currentTier();
    if (TierPolicy.allows(tier, feature)) return true;
    // 单次判局通行证：临时开放判局与导出相关
    if (await singleJudgmentActive()) {
      return feature == AppFeature.judgmentReport ||
          feature == AppFeature.coreTheoryDetail;
    }
    return false;
  }
}
