mirrored_repositories/Expenses_Tracker_App/packages/expense_repository/lib/src
import 'dart:developer';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:expense_repository/constants/collections.dart';
import 'package:expense_repository/expense_repository.dart';
import 'package:firebase_auth/firebase_auth.dart';

class FirebaseExpenseRepo implements ExpenseRepository {
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  final CollectionReference expenseCollection =
      FirebaseFirestore.instance.collection(Collections.expenses);

  @override
  Future<void> createExpense(Expense expense) async {
    expense.userId = _firebaseAuth.currentUser!.uid;
    try {
      await expenseCollection
          .doc(expense.expenseId)
          .set(expense.toEntity().toDocument());
    } catch (e) {
      log(e.toString());
      rethrow;
    }
  }

  @override
  Future<List<Expense>> getExpenses(Expense expense) async {
    expense.userId = _firebaseAuth.currentUser!.uid;
    try {
      final QuerySnapshot querySnapshot = await expenseCollection
          .where("userId", isEqualTo: expense.userId)
          .get();
      return querySnapshot.docs.map((DocumentSnapshot doc) {
        final expenseData = doc.data() as Map<String, dynamic>;
        expense.expenseId = doc.id;
        return Expense.fromEntity(ExpenseEntity.fromDocument(expenseData));
      }).toList();
    } catch (e) {
      log(e.toString());
      rethrow;
    }
  }

  @override
  Future<void> deleteExpenses(Expense expense) async {
    expense.userId = _firebaseAuth.currentUser!.uid;
    await expenseCollection.doc(expense.expenseId).delete();
  }

  @override
  Future<void> updateExpenses(Expense expense) async {
    expense.userId = _firebaseAuth.currentUser!.uid;
    await expenseCollection.doc(expense.expenseId).update(expense.toMap());
  }
}
