import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:kasy_kit/core/home_widgets/home_widget_mywidget_service.dart';
import 'package:kasy_kit/core/shared_preferences/shared_preferences.dart';
import 'package:kasy_kit/core/states/user_state_notifier.dart';
import 'package:kasy_kit/features/authentication/api/authentication_api.dart';
import 'package:kasy_kit/features/subscription/repositories/subscription_repository.dart';
import 'package:kasy_kit/i18n/translations.g.dart';
import 'package:logger/logger.dart';

/// Generated by Kasy CLI
/// ----
/// Background task callback for workmanager
/// This allows updating home widgets even when the app is in the background
@pragma('vm:entry-point')
Future<void> homeWidgetCallbackDispatcher() async {
  try {
    Logger().i('🔄 Home Widget background task triggered');
    final globalContainer = ProviderContainer();
    final sharedPreferences = globalContainer.read(sharedPreferencesProvider);
    await sharedPreferences.init();
    // Restore the user's saved app locale so the widget renders text in the
    // same language as the app (not the device locale).
    final savedLocale = sharedPreferences.prefs.getString('app_locale');
    if (savedLocale != null) {
      final appLocale = AppLocale.values.firstWhere(
        (l) => l.languageCode == savedLocale,
        orElse: () => AppLocale.en,
      );
      LocaleSettings.setLocale(appLocale);
    } else {
      LocaleSettings.useDeviceLocale();
    }
    await globalContainer.read(authenticationApiProvider).init();
    await globalContainer.read(subscriptionRepositoryProvider).init();
    await globalContainer.read(userStateNotifierProvider.notifier).init();

    /// If you want to restric the background task to only run when the user is subscribed,
    /// you can use the subscription variable here.
    // final subscription = globalContainer
    //     .read(userStateNotifierProvider)
    //     .subscription;

    final myWidgetWidget = globalContainer.read(
      myWidgetHomeWidgetProvider.notifier,
    );
    await myWidgetWidget.update();

    globalContainer.dispose();
    return;
  } catch (e) {
    Logger().e('Error in background task: $e');
    return;
  }
}
