import { Router } from "express";
import { assistantMemoryService } from "../services/assistant-memory.js";
import { assertBoard, assertCompanyAccess } from "./authz.js";

export function assistantMemoryRoutes(): Router {
  const router = Router();
  const svc = assistantMemoryService();

  // GET /api/assistant-memory/:companyId — retrieve all memory facts
  router.get("/assistant-memory/:companyId", async (req, res) => {
    const { companyId } = req.params;
    assertBoard(req);
    assertCompanyAccess(req, companyId);
    const memory = await svc.get(companyId);
    res.json(memory);
  });

  // PATCH /api/assistant-memory/:companyId — append a sanitized fact
  router.patch("/assistant-memory/:companyId", async (req, res) => {
    const { companyId } = req.params;
    assertBoard(req);
    assertCompanyAccess(req, companyId);
    const { fact } = req.body as { fact?: unknown };
    if (typeof fact !== "string" || !fact.trim()) {
      res.status(400).json({ error: "fact must be a non-empty string" });
      return;
    }
    const updated = await svc.append(companyId, fact);
    res.json(updated);
  });

  // DELETE /api/assistant-memory/:companyId — clear all memory facts
  router.delete("/assistant-memory/:companyId", async (req, res) => {
    const { companyId } = req.params;
    assertBoard(req);
    assertCompanyAccess(req, companyId);
    await svc.clear(companyId);
    res.status(204).end();
  });

  return router;
}
