import { db } from '../firebase.js';
import { collection, doc, onSnapshot, query, orderBy, addDoc, updateDoc, deleteDoc, serverTimestamp } from 'firebase/firestore';

let entries = $state([]);
let _uid = null;
let _unsubscribe = null;

export function getEntries() {
  return entries;
}

export function initEntriesListener(uid) {
  if (_unsubscribe) _unsubscribe();
  _uid = uid;
  const q = query(
    collection(db, 'users', uid, 'entries'),
    orderBy('createdAt', 'desc')
  );
  _unsubscribe = onSnapshot(q, (snap) => {
    entries = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
  });
}

export async function addEntry(data) {
  if (!_uid) return null;
  const ref = await addDoc(collection(db, 'users', _uid, 'entries'), {
    ...data,
    createdAt: serverTimestamp(),
    updatedAt: serverTimestamp(),
  });
  return ref.id;
}

export async function updateEntry(id, data) {
  if (!_uid) return;
  await updateDoc(doc(db, 'users', _uid, 'entries', id), {
    ...data,
    updatedAt: serverTimestamp(),
  });
}

export async function removeEntry(id) {
  if (!_uid) return;
  await deleteDoc(doc(db, 'users', _uid, 'entries', id));
}
