import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:marco/controller/permission_controller.dart';
import 'package:marco/controller/project_controller.dart';
import 'package:marco/helpers/services/storage/local_storage.dart';
import 'package:marco/helpers/theme/theme_customizer.dart';
import 'package:marco/helpers/theme/app_theme.dart';
import 'package:url_strategy/url_strategy.dart';
import 'package:marco/helpers/services/app_logger.dart';
import 'package:marco/helpers/services/auth_service.dart';
Future<void> initializeApp() async {
  try {
    logSafe("💡 Starting app initialization...");

    setPathUrlStrategy();
    logSafe("💡 URL strategy set.");

    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color.fromARGB(255, 255, 0, 0),
      statusBarIconBrightness: Brightness.light,
    ));
    logSafe("💡 System UI overlay style set.");

    await LocalStorage.init();
    logSafe("💡 Local storage initialized.");

    // If a refresh token is found, try to refresh the JWT token
    final refreshToken = await LocalStorage.getRefreshToken();
    if (refreshToken != null && refreshToken.isNotEmpty) {
      logSafe("🔁 Refresh token found. Attempting to refresh JWT...");
      final success = await AuthService.refreshToken();

      if (!success) {
        logSafe("⚠️ Refresh token invalid or expired. Skipping controller injection.");
        // Optionally, clear tokens and force logout here if needed
      }
    } else {
      logSafe("❌ No refresh token found. Skipping refresh.");
    }

    await ThemeCustomizer.init();
    logSafe("💡 Theme customizer initialized.");

    final token = LocalStorage.getString('jwt_token');
    if (token != null && token.isNotEmpty) {
      if (!Get.isRegistered<PermissionController>()) {
        Get.put(PermissionController());
        logSafe("💡 PermissionController injected.");
      }

      if (!Get.isRegistered<ProjectController>()) {
        Get.put(ProjectController(), permanent: true);
        logSafe("💡 ProjectController injected as permanent.");
      }

      // Load data into controllers if required
      await Get.find<PermissionController>().loadData(token);
      await Get.find<ProjectController>().fetchProjects();
    } else {
      logSafe("⚠️ No valid JWT token found. Skipping controller initialization.");
    }

    AppStyle.init();
    logSafe("💡 AppStyle initialized.");

    logSafe("✅ App initialization completed successfully.");
  } catch (e, stacktrace) {
    logSafe(
      "⛔ Error during app initialization",
      level: LogLevel.error,
      error: e,
      stackTrace: stacktrace,
    );
    rethrow;
  }
}
