import 'package:cloud_firestore/cloud_firestore.dart';
import '../models/message.dart';

class MessageRepository {
  final FirebaseFirestore _firestore;

  MessageRepository({FirebaseFirestore? firestore})
      : _firestore = firestore ?? FirebaseFirestore.instance;

  // Envoyer un message
  Future<void> sendMessage({
    required String groupId,
    required String text,
    required String senderId,
    required String senderName,
  }) async {
    final message = {
      'text': text,
      'senderId': senderId,
      'senderName': senderName,
      'timestamp': FieldValue.serverTimestamp(),
      'groupId': groupId,
    };

    await _firestore
        .collection('groups')
        .doc(groupId)
        .collection('messages')
        .add(message);
  }

  // Stream des messages
  Stream<List<Message>> getMessagesStream(String groupId) {
    return _firestore
        .collection('groups')
        .doc(groupId)
        .collection('messages')
        .orderBy('timestamp', descending: false)
        .snapshots()
        .map((snapshot) {
      return snapshot.docs.map((doc) => Message.fromFirestore(doc)).toList();
    });
  }

  // Supprimer un message (marquer comme supprimé)
  Future<void> deleteMessage({
    required String groupId,
    required String messageId,
  }) async {
    await _firestore
        .collection('groups')
        .doc(groupId)
        .collection('messages')
        .doc(messageId)
        .update({
      'isDeleted': true,
      'text': '',
    });
  }

  // Modifier un message
  Future<void> updateMessage({
    required String groupId,
    required String messageId,
    required String newText,
  }) async {
    await _firestore
        .collection('groups')
        .doc(groupId)
        .collection('messages')
        .doc(messageId)
        .update({
      'text': newText,
      'editedAt': FieldValue.serverTimestamp(),
      'isEdited': true,
    });
  }

  // Ajouter une réaction
  Future<void> reactToMessage({
    required String groupId,
    required String messageId,
    required String userId,
    required String reaction,
  }) async {
    await _firestore
        .collection('groups')
        .doc(groupId)
        .collection('messages')
        .doc(messageId)
        .update({
      'reactions.$userId': reaction,
    });
  }

  // Supprimer une réaction
  Future<void> removeReaction({
    required String groupId,
    required String messageId,
    required String userId,
  }) async {
    await _firestore
        .collection('groups')
        .doc(groupId)
        .collection('messages')
        .doc(messageId)
        .update({
      'reactions.$userId': FieldValue.delete(),
    });
  }
}
