/// Shared bootstrap logic for all Kell Creations app targets.
///
/// Uses a [KcServiceFactory] to construct the appropriate services based
/// on the runtime [KcAppConfig].
library;

import 'package:flutter/foundation.dart';

import 'kc_app_config.dart';
import 'kc_app_services.dart';

/// Bootstraps app services from the runtime [KcAppConfig].
///
/// In **fake** mode the in-memory fakes are used unconditionally.
///
/// In **wordpress** mode the WooCommerce credentials are validated first.
/// If any credential is missing the app falls back to fake mode and logs a
/// warning so the developer knows what went wrong.
///
/// ## Usage
///
/// ```dart
/// final factory = KcServiceFactory<WebAppServices>(
///   createFake: () => WebAppServices.fake(),
///   createWordPress: (config) => WebAppServices.wordpress(...),
/// );
///
/// final (:services, config: effectiveConfig) = KcBootstrap.run(config, factory);
/// ```
class KcBootstrap {
  const KcBootstrap._();

  /// Creates the appropriate services for the given [config] using [factory].
  ///
  /// Returns a record containing the resolved services and the effective
  /// config (which may differ from the input when WordPress credentials are
  /// missing and a fallback to fake mode occurs).
  static ({T services, KcAppConfig config}) run<T extends KcAppServices>(
    KcAppConfig config,
    KcServiceFactory<T> factory,
  ) {
    switch (config.environment) {
      case KcAppEnvironment.fake:
        return (services: factory.createFake(), config: config);

      case KcAppEnvironment.wordpress:
        if (!config.hasWordPressConfig) {
          if (kDebugMode) {
            // ignore: avoid_print
            debugPrint(
              '⚠️  KC_ENV=wordpress but WooCommerce credentials are missing.\n'
              '    Falling back to fake mode.\n'
              '    Set KC_WC_SITE_URL, KC_WC_CONSUMER_KEY, and '
              'KC_WC_CONSUMER_SECRET via --dart-define.',
            );
          }
          final fallbackConfig = KcAppConfig(
            environment: KcAppEnvironment.fake,
            wcSiteUrl: config.wcSiteUrl,
            wcConsumerKey: config.wcConsumerKey,
            wcConsumerSecret: config.wcConsumerSecret,
          );
          return (services: factory.createFake(), config: fallbackConfig);
        }

        return (services: factory.createWordPress(config), config: config);
    }
  }
}
