/// Runtime configuration read from `--dart-define` values.
///
/// The app reads the following compile-time constants:
///
/// | Key                    | Description                                  | Default  |
/// |------------------------|----------------------------------------------|----------|
/// | `KC_ENV`               | `fake` or `wordpress`                        | `fake`   |
/// | `KC_WC_SITE_URL`       | WordPress site URL                           | (empty)  |
/// | `KC_WC_CONSUMER_KEY`   | WooCommerce REST API consumer key            | (empty)  |
/// | `KC_WC_CONSUMER_SECRET`| WooCommerce REST API consumer secret         | (empty)  |
///
/// Usage:
/// ```sh
/// flutter run -d chrome \
///   --dart-define=KC_ENV=wordpress \
///   --dart-define=KC_WC_SITE_URL=https://store.kellcreations.com \
///   --dart-define=KC_WC_CONSUMER_KEY=ck_xxx \
///   --dart-define=KC_WC_CONSUMER_SECRET=cs_xxx
/// ```
class AppConfig {
  /// The environment mode: `fake` or `wordpress`.
  final AppEnvironment environment;

  /// WordPress / WooCommerce site URL (only used in [AppEnvironment.wordpress]).
  final String wcSiteUrl;

  /// WooCommerce REST API consumer key.
  final String wcConsumerKey;

  /// WooCommerce REST API consumer secret.
  final String wcConsumerSecret;

  const AppConfig({
    required this.environment,
    required this.wcSiteUrl,
    required this.wcConsumerKey,
    required this.wcConsumerSecret,
  });

  /// Reads configuration from compile-time `--dart-define` constants.
  factory AppConfig.fromEnvironment() {
    const envString = String.fromEnvironment('KC_ENV', defaultValue: 'fake');
    const siteUrl = String.fromEnvironment('KC_WC_SITE_URL');
    const consumerKey = String.fromEnvironment('KC_WC_CONSUMER_KEY');
    const consumerSecret = String.fromEnvironment('KC_WC_CONSUMER_SECRET');

    final environment = AppEnvironment.fromString(envString);

    return AppConfig(
      environment: environment,
      wcSiteUrl: siteUrl,
      wcConsumerKey: consumerKey,
      wcConsumerSecret: consumerSecret,
    );
  }

  /// Whether the WordPress configuration values are all present and non-empty.
  bool get hasWordPressConfig =>
      wcSiteUrl.isNotEmpty && wcConsumerKey.isNotEmpty && wcConsumerSecret.isNotEmpty;

  /// A human-readable label for the current environment (e.g. for badges).
  String get environmentLabel => environment.label;
}

/// The supported runtime environments.
enum AppEnvironment {
  /// In-memory fakes – no network calls.
  fake('fake', 'FAKE'),

  /// Real WooCommerce backend.
  wordpress('wordpress', 'WP');

  final String key;
  final String label;

  const AppEnvironment(this.key, this.label);

  /// Parses a string into an [AppEnvironment], defaulting to [fake].
  static AppEnvironment fromString(String value) {
    for (final env in values) {
      if (env.key == value.toLowerCase()) return env;
    }
    return fake;
  }
}
