import 'package:cloud_firestore/cloud_firestore.dart';

import 'jsonable.dart';

class ItemService<T extends Jsonable> {
  final String collectionName;
  final T Function(Map<String, dynamic>) fromJson;
  late final _itemCollection =
      FirebaseFirestore.instance.collection(collectionName).withConverter(
    fromFirestore: (snapshot, options) {
      final json = snapshot.data() ?? {};
      json['id'] = snapshot.id;
      return fromJson(json);
    },
    toFirestore: (value, options) {
      final json = value.toJson();
      json.remove('id');
      return json;
    },
  );

  ItemService({required this.collectionName, required this.fromJson});

  get itemCollection => _itemCollection;

  Future<DocumentReference<T>> createItem(T item) {
    return _itemCollection.add(item);
  }

  Future<void> createItemWithId(T item, String id) {
    return _itemCollection.doc(id).set(item);
  }

  Future<void> updateItem(T item) {
    assert(item.id != null);
    return itemCollection.doc(item.id).set(item);
  }

  Future<void> deleteItem(String itemId) {
    return _itemCollection.doc(itemId).delete();
  }

  Future<T?> getItemById(String id) async {
    try {
      final docSnapshot = await itemCollection.doc(id).get();
      return docSnapshot.data();
    } catch (message) {
      throw 'Error finding item: $message';
    }
  }
}
