import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:travel_mate/services/error_service.dart';
import '../models/account.dart';

class AccountService {
  final _errorService = ErrorService();
  final FirebaseFirestore _firestore = FirebaseFirestore.instance;

  Stream<List<Account>> getAccountsStream() {
    return _firestore.collection('accounts').snapshots().map((snapshot) {
      return snapshot.docs.map((doc) {
        return Account.fromMap(doc.data(), doc.id);
      }).toList();
    });
  }

  Future<bool> createAccount(Account account) async {
    try {
      await _firestore.collection('accounts').add(account.toMap());
      return true;
    } catch (e) {
      _errorService.logError('Erreur lors de la création du compte: $e', StackTrace.current);
      return false;
    }
  }

  Future<bool> updateAccount(Account account) async {
    try {
      await _firestore.collection('accounts').doc(account.id).update(account.toMap());
      return true;
    } catch (e) {
      _errorService.logError('Erreur lors de la mise à jour du compte: $e', StackTrace.current);
      return false;
    }
  }

  Future<bool> deleteAccount(String accountId) async {
    try {
      await _firestore.collection('accounts').doc(accountId).delete();
      return true;
    } catch (e) {
      _errorService.logError('Erreur lors de la suppression du compte: $e', StackTrace.current);
      return false;
    }
  }
 

  Stream<List<Account>> getAccountsStreamByUser(String userId) {
    return _firestore
        .collection('accounts')
        .where('members', arrayContains: userId)
        .snapshots()
        .map((snapshot) {
      return snapshot.docs.map((doc) {
        final account = Account.fromMap(doc.data(), doc.id);
        _errorService.logError('Compte: ${account.name}', StackTrace.current);
        return account;
      }).toList();
    });
  }

}