/// Provider: Member Card Provider
///
/// Manages the state of the member card data using Riverpod.
/// Provides access to member card information 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/member_card.dart';
import 'package:worker/features/home/domain/usecases/get_member_card.dart';

part 'member_card_provider.g.dart';

/// Member Card Provider
///
/// Fetches and caches the current user's member card.
/// Automatically handles loading, error, and data states.
///
/// Usage:
/// ```dart
/// // In a ConsumerWidget
/// final memberCardAsync = ref.watch(memberCardProvider);
///
/// memberCardAsync.when(
///   data: (memberCard) => MemberCardWidget(memberCard: memberCard),
///   loading: () => const CustomLoadingIndicator(),
///   error: (error, stack) => ErrorWidget(error),
/// );
/// ```
@riverpod
class MemberCardNotifier extends _$MemberCardNotifier {
  @override
  Future<MemberCard> build() async {
    // Initialize dependencies
    final localDataSource = const HomeLocalDataSourceImpl();
    final repository = HomeRepositoryImpl(localDataSource: localDataSource);
    final useCase = GetMemberCard(repository);

    // Fetch member card
    return await useCase();
  }

  /// Refresh member card 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 = GetMemberCard(repository);

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