import 'dart:async';
import 'package:prosapp_web_app/models/chat_entity.dart';
import 'package:prosapp_web_app/models/message_entity.dart';
import 'package:prosapp_web_app/services/api_service.dart';

// ponytail: kept filename to avoid breaking imports
class FirebaseChatRepository {
  final _api = ApiService.instance;

  Stream<ChatEntity?> getChatById(String serviceId, String professionalId) async* {
    String? chatId;
    while (true) {
      try {
        if (chatId == null) {
          // Create/get the chat first; backend identifies chats by professional user ID
          final chatData = await _api.post('/chat/start/$professionalId', {});
          chatId = chatData['id'] as String;
          final messages = _parseMessages(chatData['messages']);
          yield ChatEntity(
            id: chatId,
            userId: chatData['user_id'] as String,
            professionalId: chatData['professional_id'] as String,
            messages: messages,
          );
        } else {
          final res = await _api.get('/chat/$chatId/messages');
          final list = (res is Map ? res['data'] : res) as List;
          final messages = list.map((e) => MessageEntity.fromDocument(e as Map<String, dynamic>)).toList();
          yield ChatEntity(
            id: chatId,
            userId: '',
            professionalId: professionalId,
            messages: messages,
          );
        }
      } catch (_) {
        yield null;
      }
      await Future.delayed(const Duration(seconds: 3));
    }
  }

  Future<ChatEntity> createNewChat(String serviceId, String userId, String professionalId) async {
    final data = await _api.post('/chat/start/$professionalId', {});
    return ChatEntity(
      id: data['id'] as String,
      userId: data['user_id'] as String,
      professionalId: data['professional_id'] as String,
      messages: _parseMessages(data['messages']),
    );
  }

  Future<void> sendMessage(String chatId, MessageEntity message) async {
    await _api.post('/chat/$chatId/message', {'content': message.content});
  }

  List<MessageEntity> _parseMessages(dynamic raw) {
    if (raw is! List) return [];
    return raw.map((e) => MessageEntity.fromDocument(e as Map<String, dynamic>)).toList();
  }
}
