import { collection, doc, getDoc, getDocs, setDoc, updateDoc, deleteDoc, query, where, orderBy, WriteBatch, writeBatch, } from 'firebase/firestore' import { db } from './firebase' type FirestoreData = Record /** * Generic function to add or update a document */ export async function setDocument( collectionName: string, docId: string, data: T, merge = true ): Promise { try { await setDoc(doc(db, collectionName, docId), data, { merge }) } catch (error) { console.error(`Error setting document in ${collectionName}:`, error) throw error } } /** * Generic function to get a single document */ export async function getDocument( collectionName: string, docId: string ): Promise { try { const docRef = doc(db, collectionName, docId) const docSnapshot = await getDoc(docRef) return (docSnapshot.exists() ? docSnapshot.data() : null) as T | null } catch (error) { console.error(`Error getting document from ${collectionName}:`, error) throw error } } /** * Generic function to get all documents from a collection */ export async function getDocuments( collectionName: string ): Promise { try { const querySnapshot = await getDocs(collection(db, collectionName)) return querySnapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() } as T)) } catch (error) { console.error(`Error getting documents from ${collectionName}:`, error) throw error } } /** * Generic function to query documents with conditions */ export async function queryDocuments( collectionName: string, constraints: any[] ): Promise { try { const q = query(collection(db, collectionName), ...constraints) const querySnapshot = await getDocs(q) return querySnapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() } as T)) } catch (error) { console.error(`Error querying ${collectionName}:`, error) throw error } } /** * Generic function to update a document */ export async function updateDocument>( collectionName: string, docId: string, data: T ): Promise { try { await updateDoc(doc(db, collectionName, docId), data) } catch (error) { console.error(`Error updating document in ${collectionName}:`, error) throw error } } /** * Generic function to delete a document */ export async function deleteDocument( collectionName: string, docId: string ): Promise { try { await deleteDoc(doc(db, collectionName, docId)) } catch (error) { console.error(`Error deleting document from ${collectionName}:`, error) throw error } } /** * Batch write operations */ export function createWriteBatch(): WriteBatch { return writeBatch(db) } export async function commitBatch(batch: WriteBatch): Promise { try { await batch.commit() } catch (error) { console.error('Error committing batch write:', error) throw error } }