/// Provider: Promotions Provider
///
/// Manages the state of promotions data using Riverpod.
/// Provides access to active promotions throughout the app.
///
/// Uses AsyncNotifierProvider for automatic loading, error, and data states.
library;

import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:worker/features/home/data/datasources/home_local_datasource.dart';
import 'package:worker/features/home/data/repositories/home_repository_impl.dart';
import 'package:worker/features/home/domain/entities/promotion.dart';
import 'package:worker/features/home/domain/usecases/get_promotions.dart';

part 'promotions_provider.g.dart';

/// Promotions Provider
///
/// Fetches and caches the list of active promotions.
/// Automatically handles loading, error, and data states.
///
/// Usage:
/// ```dart
/// // In a ConsumerWidget
/// final promotionsAsync = ref.watch(promotionsProvider);
///
/// promotionsAsync.when(
///   data: (promotions) => PromotionSlider(promotions: promotions),
///   loading: () => CircularProgressIndicator(),
///   error: (error, stack) => ErrorWidget(error),
/// );
/// ```
@riverpod
class PromotionsNotifier extends _$PromotionsNotifier {
  @override
  Future<List<Promotion>> build() async {
    // Initialize dependencies
    final localDataSource = const HomeLocalDataSourceImpl();
    final repository = HomeRepositoryImpl(localDataSource: localDataSource);
    final useCase = GetPromotions(repository);

    // Fetch promotions (only active ones)
    return await useCase();
  }

  /// Refresh promotions data
  ///
  /// Forces a refresh from the server (when API is available).
  /// Updates the cached state with fresh data.
  Future<void> refresh() async {
    // Set loading state
    state = const AsyncValue.loading();

    // Fetch fresh data
    state = await AsyncValue.guard(() async {
      final localDataSource = const HomeLocalDataSourceImpl();
      final repository = HomeRepositoryImpl(localDataSource: localDataSource);
      final useCase = GetPromotions(repository);

      return await useCase.refresh();
    });
  }
}
