import { db } from "./firebase.config";
import {
  collection,
  addDoc,
  getDocs,
  deleteDoc,
  doc,
} from "firebase/firestore";

import { MemoryChunk } from "./types";
import { getEmbedding } from "./embedding";

const CHUNKS = "memory_chunks";

// ✍️ Write a new memory
export async function writeMemory(
  chunk: Omit<MemoryChunk, "embedding" | "timestamp">
) {
  const embedding = await getEmbedding(chunk.text);
  const timestamp = new Date().toISOString();

  const fullChunk: MemoryChunk = { ...chunk, embedding, timestamp };
  console.log("🧠 Final memory chunk to write:", fullChunk);

  const ref = await addDoc(collection(db, CHUNKS), fullChunk);
  return { id: ref.id };
}

// 🔍 TEMP DEBUG: Fetch ALL documents and filter manually
export async function queryMemory(userId: string, projectId: string) {
  const snapshot = await getDocs(collection(db, CHUNKS));
  console.log(`🧪 [queryMemory] Total Firestore docs: ${snapshot.size}`);

  const allDocs = snapshot.docs.map((docSnap) => ({
    ...(docSnap.data() as MemoryChunk),
    id: docSnap.id,
  }));

  allDocs.forEach((doc) => {
    console.log("📄 Raw doc:", {
      id: doc.id,
      userId: doc.userId,
      projectId: doc.projectId,
      text: doc.text,
    });
  });

  const results = allDocs.filter(
    (doc) =>
      doc.userId === userId &&
      doc.projectId === projectId
  );

  console.log(`🎯 Matching results for ${userId}/${projectId}:`, results.length);

  return results;
}

// 🗑️ Delete a memory by ID
export async function deleteMemory(chunkId: string) {
  await deleteDoc(doc(db, CHUNKS, chunkId));
  return { success: true };
}
