import 'dart:convert';

/// 网站配置信息
class KRSiteConfig {
  final KRSiteInfo site;
  final KRVerifyConfig verify;
  final KRAuthConfig auth;
  final KRInviteConfig invite;
  final KRCurrencyConfig currency;
  final KRSubscribeConfig subscribe;
  final KRVerifyCodeConfig verifyCode;
  final List<String> oauthMethods;
  final bool webAd;

  KRSiteConfig({
    required this.site,
    required this.verify,
    required this.auth,
    required this.invite,
    required this.currency,
    required this.subscribe,
    required this.verifyCode,
    required this.oauthMethods,
    required this.webAd,
  });

  factory KRSiteConfig.fromJson(Map<String, dynamic> json) {
    return KRSiteConfig(
      site: KRSiteInfo.fromJson(json['site'] ?? {}),
      verify: KRVerifyConfig.fromJson(json['verify'] ?? {}),
      auth: KRAuthConfig.fromJson(json['auth'] ?? {}),
      invite: KRInviteConfig.fromJson(json['invite'] ?? {}),
      currency: KRCurrencyConfig.fromJson(json['currency'] ?? {}),
      subscribe: KRSubscribeConfig.fromJson(json['subscribe'] ?? {}),
      verifyCode: KRVerifyCodeConfig.fromJson(json['verify_code'] ?? {}),
      oauthMethods: List<String>.from(json['oauth_methods'] ?? []),
      webAd: json['web_ad'] ?? false,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'site': site.toJson(),
      'verify': verify.toJson(),
      'auth': auth.toJson(),
      'invite': invite.toJson(),
      'currency': currency.toJson(),
      'subscribe': subscribe.toJson(),
      'verify_code': verifyCode.toJson(),
      'oauth_methods': oauthMethods,
      'web_ad': webAd,
    };
  }
}

/// 站点信息
class KRSiteInfo {
  final String host;
  final String siteName;
  final String siteDesc;
  final String siteLogo;
  final String keywords;
  final String customHtml;
  final String customData;
  final String crispId;
  final String deviceLimit;

  KRSiteInfo({
    required this.host,
    required this.siteName,
    required this.siteDesc,
    required this.siteLogo,
    required this.keywords,
    required this.customHtml,
    required this.customData,
    required this.crispId,
    required this.deviceLimit,
  });

  factory KRSiteInfo.fromJson(Map<String, dynamic> json) {
    String crispId = '0';
    String deviceLimit = '0';

    // 尝试解析 custom_data 中的 deviceLimit
    try {
      final customDataStr = json['custom_data'] ?? '';
      if (customDataStr.isNotEmpty) {
        final customDataJson = jsonDecode(customDataStr) as Map<String, dynamic>;
        deviceLimit = (customDataJson['deviceLimit'] ?? 0).toString();
      }
    } catch (e) {
      // 解析失败时使用默认值
    }
    return KRSiteInfo(
      host: json['host'] ?? '',
      siteName: json['site_name'] ?? '',
      siteDesc: json['site_desc'] ?? '',
      siteLogo: json['site_logo'] ?? '',
      keywords: json['keywords'] ?? '',
      customHtml: json['custom_html'] ?? '',
      customData: json['custom_data'] ?? '',
      crispId: crispId,
      deviceLimit: deviceLimit,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'host': host,
      'site_name': siteName,
      'site_desc': siteDesc,
      'site_logo': siteLogo,
      'keywords': keywords,
      'custom_html': customHtml,
      'custom_data': customData,
    };
  }
}

/// 验证配置
class KRVerifyConfig {
  final String turnstileSiteKey;
  final bool enableLoginVerify;
  final bool enableRegisterVerify;
  final bool enableResetPasswordVerify;

  KRVerifyConfig({
    required this.turnstileSiteKey,
    required this.enableLoginVerify,
    required this.enableRegisterVerify,
    required this.enableResetPasswordVerify,
  });

  factory KRVerifyConfig.fromJson(Map<String, dynamic> json) {
    return KRVerifyConfig(
      turnstileSiteKey: json['turnstile_site_key'] ?? '',
      enableLoginVerify: json['enable_login_verify'] ?? false,
      enableRegisterVerify: json['enable_register_verify'] ?? false,
      enableResetPasswordVerify: json['enable_reset_password_verify'] ?? false,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'turnstile_site_key': turnstileSiteKey,
      'enable_login_verify': enableLoginVerify,
      'enable_register_verify': enableRegisterVerify,
      'enable_reset_password_verify': enableResetPasswordVerify,
    };
  }
}

/// 认证配置
class KRAuthConfig {
  final KRMobileAuth mobile;
  final KREmailAuth email;
  final KRDeviceAuth device;
  final KRRegisterAuth register;

  KRAuthConfig({
    required this.mobile,
    required this.email,
    required this.device,
    required this.register,
  });

  factory KRAuthConfig.fromJson(Map<String, dynamic> json) {
    return KRAuthConfig(
      mobile: KRMobileAuth.fromJson(json['mobile'] ?? {}),
      email: KREmailAuth.fromJson(json['email'] ?? {}),
      device: KRDeviceAuth.fromJson(json['device'] ?? {}),
      register: KRRegisterAuth.fromJson(json['register'] ?? {}),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'mobile': mobile.toJson(),
      'email': email.toJson(),
      'device': device.toJson(),
      'register': register.toJson(),
    };
  }
}

/// 手机号认证配置
class KRMobileAuth {
  final bool enable;
  final bool enableWhitelist;
  final List<String> whitelist;

  KRMobileAuth({
    required this.enable,
    required this.enableWhitelist,
    required this.whitelist,
  });

  factory KRMobileAuth.fromJson(Map<String, dynamic> json) {
    return KRMobileAuth(
      enable: json['enable'] ?? false,
      enableWhitelist: json['enable_whitelist'] ?? false,
      whitelist: List<String>.from(json['whitelist'] ?? []),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'enable': enable,
      'enable_whitelist': enableWhitelist,
      'whitelist': whitelist,
    };
  }
}

/// 邮箱认证配置
class KREmailAuth {
  final bool enable;
  final bool enableVerify;
  final bool enableDomainSuffix;
  final String domainSuffixList;

  KREmailAuth({
    required this.enable,
    required this.enableVerify,
    required this.enableDomainSuffix,
    required this.domainSuffixList,
  });

  factory KREmailAuth.fromJson(Map<String, dynamic> json) {
    return KREmailAuth(
      enable: json['enable'] ?? false,
      enableVerify: json['enable_verify'] ?? false,
      enableDomainSuffix: json['enable_domain_suffix'] ?? false,
      domainSuffixList: json['domain_suffix_list'] ?? '',
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'enable': enable,
      'enable_verify': enableVerify,
      'enable_domain_suffix': enableDomainSuffix,
      'domain_suffix_list': domainSuffixList,
    };
  }
}

/// 设备认证配置
class KRDeviceAuth {
  final bool enable;
  final bool showAds;
  final bool enableSecurity;
  final bool onlyRealDevice;

  KRDeviceAuth({
    required this.enable,
    required this.showAds,
    required this.enableSecurity,
    required this.onlyRealDevice,
  });

  factory KRDeviceAuth.fromJson(Map<String, dynamic> json) {
    return KRDeviceAuth(
      enable: json['enable'] ?? false,
      showAds: json['show_ads'] ?? false,
      enableSecurity: json['enable_security'] ?? false,
      onlyRealDevice: json['only_real_device'] ?? false,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'enable': enable,
      'show_ads': showAds,
      'enable_security': enableSecurity,
      'only_real_device': onlyRealDevice,
    };
  }
}

/// 注册认证配置
class KRRegisterAuth {
  final bool stopRegister;
  final bool enableIpRegisterLimit;
  final int ipRegisterLimit;
  final int ipRegisterLimitDuration;

  KRRegisterAuth({
    required this.stopRegister,
    required this.enableIpRegisterLimit,
    required this.ipRegisterLimit,
    required this.ipRegisterLimitDuration,
  });

  factory KRRegisterAuth.fromJson(Map<String, dynamic> json) {
    return KRRegisterAuth(
      stopRegister: json['stop_register'] ?? false,
      enableIpRegisterLimit: json['enable_ip_register_limit'] ?? false,
      ipRegisterLimit: json['ip_register_limit'] ?? 0,
      ipRegisterLimitDuration: json['ip_register_limit_duration'] ?? 0,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'stop_register': stopRegister,
      'enable_ip_register_limit': enableIpRegisterLimit,
      'ip_register_limit': ipRegisterLimit,
      'ip_register_limit_duration': ipRegisterLimitDuration,
    };
  }
}

/// 邀请配置
class KRInviteConfig {
  final bool forcedInvite;
  final double referralPercentage;
  final bool onlyFirstPurchase;

  KRInviteConfig({
    required this.forcedInvite,
    required this.referralPercentage,
    required this.onlyFirstPurchase,
  });

  factory KRInviteConfig.fromJson(Map<String, dynamic> json) {
    return KRInviteConfig(
      forcedInvite: json['forced_invite'] ?? false,
      referralPercentage: (json['referral_percentage'] ?? 0).toDouble(),
      onlyFirstPurchase: json['only_first_purchase'] ?? false,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'forced_invite': forcedInvite,
      'referral_percentage': referralPercentage,
      'only_first_purchase': onlyFirstPurchase,
    };
  }
}

/// 货币配置
class KRCurrencyConfig {
  final String currencyUnit;
  final String currencySymbol;

  KRCurrencyConfig({
    required this.currencyUnit,
    required this.currencySymbol,
  });

  factory KRCurrencyConfig.fromJson(Map<String, dynamic> json) {
    return KRCurrencyConfig(
      currencyUnit: json['currency_unit'] ?? '',
      currencySymbol: json['currency_symbol'] ?? '',
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'currency_unit': currencyUnit,
      'currency_symbol': currencySymbol,
    };
  }
}

/// 订阅配置
class KRSubscribeConfig {
  final bool singleModel;
  final String subscribePath;
  final String subscribeDomain;
  final bool panDomain;
  final bool userAgentLimit;
  final String userAgentList;

  KRSubscribeConfig({
    required this.singleModel,
    required this.subscribePath,
    required this.subscribeDomain,
    required this.panDomain,
    required this.userAgentLimit,
    required this.userAgentList,
  });

  factory KRSubscribeConfig.fromJson(Map<String, dynamic> json) {
    return KRSubscribeConfig(
      singleModel: json['single_model'] ?? false,
      subscribePath: json['subscribe_path'] ?? '',
      subscribeDomain: json['subscribe_domain'] ?? '',
      panDomain: json['pan_domain'] ?? false,
      userAgentLimit: json['user_agent_limit'] ?? false,
      userAgentList: json['user_agent_list'] ?? '',
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'single_model': singleModel,
      'subscribe_path': subscribePath,
      'subscribe_domain': subscribeDomain,
      'pan_domain': panDomain,
      'user_agent_limit': userAgentLimit,
      'user_agent_list': userAgentList,
    };
  }
}

/// 验证码配置
class KRVerifyCodeConfig {
  final int verifyCodeInterval;

  KRVerifyCodeConfig({
    required this.verifyCodeInterval,
  });

  factory KRVerifyCodeConfig.fromJson(Map<String, dynamic> json) {
    return KRVerifyCodeConfig(
      verifyCodeInterval: json['verify_code_interval'] ?? 60,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'verify_code_interval': verifyCodeInterval,
    };
  }
}
