import 'package:prosapp_web_app/models/comment_entity.dart';
import 'package:prosapp_web_app/models/score_entity.dart';
import 'package:prosapp_web_app/services/api_service.dart';

// ponytail: renamed to ApiScoreRepository but kept filename to avoid breaking imports
class FirebaseScoreRepository {
  final _api = ApiService.instance;

  Future<ReputationEntity> getReputationByUserId(String userId) async {
    try {
      final data = await _api.get('/comments/reputation/$userId');
      return ReputationEntity.fromDocument(data as Map<String, dynamic>);
    } catch (e) {
      return const ReputationEntity(total: 0, average: 0, totalPro: 0, averagePro: 0);
    }
  }

  Stream<ReputationEntity> streamReputation(String userId) async* {
    while (true) {
      yield await getReputationByUserId(userId);
      await Future.delayed(const Duration(seconds: 10));
    }
  }

  Stream<List<CommentEntity>> getScoresForUser(String userId) async* {
    while (true) {
      try {
        final data = await _api.get('/comments/user/$userId') as List;
        yield data.map((e) => CommentEntity.fromDocument(e as Map<String, dynamic>)).toList();
      } catch (_) {
        yield [];
      }
      await Future.delayed(const Duration(seconds: 10));
    }
  }

  Stream<List<CommentEntity>> getScoresForProfessional(String userId) async* {
    while (true) {
      try {
        final data = await _api.get('/comments/professional/$userId') as List;
        yield data.map((e) => CommentEntity.fromDocument(e as Map<String, dynamic>)).toList();
      } catch (_) {
        yield [];
      }
      await Future.delayed(const Duration(seconds: 10));
    }
  }

  Future<void> addComment(CommentEntity comment) async {
    await _api.post('/comments', comment.toDocument());
  }
}
