/// Providers: Points Records
///
/// State management for points records feature.
library;

import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:worker/features/loyalty/data/datasources/points_record_remote_datasource.dart';
import 'package:worker/features/loyalty/data/repositories/points_record_repository_impl.dart';
import 'package:worker/features/loyalty/domain/entities/points_record.dart';
import 'package:worker/features/loyalty/domain/repositories/points_record_repository.dart';
import 'package:worker/features/loyalty/domain/usecases/get_points_records.dart';

part 'points_records_provider.g.dart';

// ============================================================================
// Data Layer Providers
// ============================================================================

/// Points Record Remote Data Source Provider
@riverpod
PointsRecordRemoteDataSource pointsRecordRemoteDataSource(Ref ref) {
  return PointsRecordRemoteDataSourceImpl();
}

/// Points Record Repository Provider
@riverpod
PointsRecordRepository pointsRecordRepository(Ref ref) {
  final remoteDataSource = ref.watch(pointsRecordRemoteDataSourceProvider);
  return PointsRecordRepositoryImpl(remoteDataSource);
}

/// Get Points Records Use Case Provider
@riverpod
GetPointsRecords getPointsRecords(Ref ref) {
  final repository = ref.watch(pointsRecordRepositoryProvider);
  return GetPointsRecords(repository);
}

// ============================================================================
// Presentation Layer Providers
// ============================================================================

/// All Points Records Provider (AsyncNotifier)
@riverpod
class AllPointsRecords extends _$AllPointsRecords {
  @override
  Future<List<PointsRecord>> build() async {
    final useCase = ref.watch(getPointsRecordsProvider);
    return await useCase();
  }

  /// Refresh points records
  Future<void> refresh() async {
    state = const AsyncValue.loading();
    state = await AsyncValue.guard(() async {
      final useCase = ref.read(getPointsRecordsProvider);
      return await useCase();
    });
  }
}

/// Points Records Filter State Provider
@riverpod
class PointsRecordsFilter extends _$PointsRecordsFilter {
  @override
  ({String searchQuery, PointsStatus? selectedStatus}) build() {
    return (searchQuery: '', selectedStatus: null);
  }

  /// Update search query
  void updateSearchQuery(String query) {
    state = (searchQuery: query, selectedStatus: state.selectedStatus);
  }

  /// Select status filter
  void selectStatus(PointsStatus? status) {
    state = (searchQuery: state.searchQuery, selectedStatus: status);
  }

  /// Clear status filter
  void clearStatusFilter() {
    state = (searchQuery: state.searchQuery, selectedStatus: null);
  }
}

/// Filtered Points Records Provider
@riverpod
AsyncValue<List<PointsRecord>> filteredPointsRecords(Ref ref) {
  final dataAsync = ref.watch(allPointsRecordsProvider);
  final filter = ref.watch(pointsRecordsFilterProvider);

  return dataAsync.whenData((records) {
    var filtered = records;

    // Apply status filter
    if (filter.selectedStatus != null) {
      filtered = filtered
          .where((record) => record.status == filter.selectedStatus)
          .toList();
    }

    // Apply search filter
    if (filter.searchQuery.isNotEmpty) {
      final query = filter.searchQuery.toLowerCase();
      filtered = filtered.where((record) {
        final idMatch = record.recordId.toLowerCase().contains(query);
        final invoiceMatch = record.invoiceNumber.toLowerCase().contains(query);
        final storeMatch = record.storeName.toLowerCase().contains(query);
        return idMatch || invoiceMatch || storeMatch;
      }).toList();
    }

    // Sort by submission date (newest first)
    filtered.sort((a, b) => b.submittedAt.compareTo(a.submittedAt));

    return filtered;
  });
}
