/// Providers: Points History
///
/// Riverpod providers for managing points history state.
library;

import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:worker/features/loyalty/data/datasources/points_history_local_datasource.dart';
import 'package:worker/features/loyalty/data/models/loyalty_point_entry_model.dart';

part 'points_history_provider.g.dart';

/// Points History Local Data Source Provider
@riverpod
PointsHistoryLocalDataSource pointsHistoryLocalDataSource(Ref ref) {
  return PointsHistoryLocalDataSource();
}

/// Points History Provider
///
/// Provides list of all points history entries from local data source.
@riverpod
class PointsHistory extends _$PointsHistory {
  @override
  Future<List<LoyaltyPointEntryModel>> build() async {
    final datasource = ref.read(pointsHistoryLocalDataSourceProvider);

    // Seed mock data on first load
    final entries = await datasource.getAllEntries();
    if (entries.isEmpty) {
      await datasource.seedMockEntries();
      return await datasource.getAllEntries();
    }

    return entries;
  }

  /// Refresh points history
  Future<void> refresh() async {
    state = const AsyncValue.loading();
    state = await AsyncValue.guard(() async {
      return await ref
          .read(pointsHistoryLocalDataSourceProvider)
          .getAllEntries();
    });
  }
}
