// pages/api/query.ts
import type { NextApiRequest, NextApiResponse } from "next";
import { db } from "@/lib/firebase.config";
import { collection, getDocs, query, where } from "firebase/firestore";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const { userId, projectId } = req.query;

  if (!userId || !projectId) {
    return res.status(400).json({ error: "Missing userId or projectId" });
  }

  try {
    const q = query(
      collection(db, "memory_chunks"),
      where("userId", "==", userId),
      where("projectId", "==", projectId)
    );
    const snapshot = await getDocs(q);
    const results = snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id }));
    res.status(200).json({ results });
  } catch (err: any) {
    console.error("❌ Error in /api/query:", err);
    res.status(500).json({ error: err.message });
  }
}
