import 'package:flutter/foundation.dart';

import 'app_config.dart';
import 'app_services.dart';

/// Bootstraps [AppServices] from the runtime [AppConfig].
///
/// 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.
class Bootstrap {
  const Bootstrap._();

  /// Creates the appropriate [AppServices] for the given [config].
  ///
  /// 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 ({AppServices services, AppConfig config}) run(AppConfig config) {
    switch (config.environment) {
      case AppEnvironment.fake:
        return (services: AppServices.fake(), config: config);

      case AppEnvironment.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 = AppConfig(
            environment: AppEnvironment.fake,
            wcSiteUrl: config.wcSiteUrl,
            wcConsumerKey: config.wcConsumerKey,
            wcConsumerSecret: config.wcConsumerSecret,
          );
          return (services: AppServices.fake(), config: fallbackConfig);
        }

        return (
          services: AppServices.wordpress(
            siteUrl: config.wcSiteUrl,
            consumerKey: config.wcConsumerKey,
            consumerSecret: config.wcConsumerSecret,
          ),
          config: config,
        );
    }
  }
}
