import type { NextApiRequest, NextApiResponse } from "next";
import { db } from "@/lib/firebase.config";
import { collection, addDoc } from "firebase/firestore";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== "POST") {
    return res.status(405).json({ error: "Method not allowed" });
  }

  try {
    const { userId, projectId, text, type, tags, embedding, timestamp } = req.body;

    if (!userId || !projectId || !text || !type || !Array.isArray(tags)) {
      return res.status(400).json({ error: "Missing required memory fields" });
    }

    const docRef = await addDoc(collection(db, "memory_chunks"), {
      userId,
      projectId,
      text,
      type,
      tags,
      embedding: embedding || [],
      timestamp: timestamp || new Date().toISOString(),
    });

    res.status(200).json({ id: docRef.id });
  } catch (err: any) {
    console.error("🔥 Write API error:", err);
    res.status(500).json({ error: err.message });
  }
}
