import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:worker/core/network/dio_client.dart';
import 'package:worker/features/price_policy/data/datasources/price_policy_remote_datasource.dart';
import 'package:worker/features/price_policy/data/repositories/price_policy_repository_impl.dart';
import 'package:worker/features/price_policy/domain/entities/price_document.dart';
import 'package:worker/features/price_policy/domain/repositories/price_policy_repository.dart';

part 'price_documents_provider.g.dart';

/// Provider for price policy repository
@riverpod
Future<PricePolicyRepository> pricePolicyRepository(Ref ref) async {
  final dioClient = await ref.watch(dioClientProvider.future);
  final remoteDataSource = PricePolicyRemoteDataSourceImpl(dioClient);
  return PricePolicyRepositoryImpl(remoteDataSource: remoteDataSource);
}

/// Provider for all price policy documents
@riverpod
Future<List<PriceDocument>> priceDocuments(Ref ref) async {
  final repository = await ref.watch(pricePolicyRepositoryProvider.future);
  return repository.getAllDocuments();
}

/// Provider for filtered documents by category with file path management
@riverpod
class FilteredPriceDocuments extends _$FilteredPriceDocuments {
  @override
  Future<List<PriceDocument>> build(DocumentCategory category) async {
    final repository = await ref.watch(pricePolicyRepositoryProvider.future);
    return repository.getDocumentsByCategory(category);
  }

  /// Update a document's file path after download
  void updateDocumentFilePath(String documentTitle, String filePath) {
    state = state.whenData((documents) {
      return documents.map((doc) {
        if (doc.title == documentTitle) {
          return doc.copyWith(filePath: filePath);
        }
        return doc;
      }).toList();
    });
  }

  /// Refresh documents
  Future<void> refresh() async {
    state = const AsyncValue.loading();
    state = await AsyncValue.guard(() async {
      final repository = await ref.read(pricePolicyRepositoryProvider.future);
      return repository.getDocumentsByCategory(category);
    });
  }
}
