// [nexus] Assistant-to-PM handoff route (Plan 33-03)
import { Router } from "express";
import type { Db } from "@paperclipai/db";
import { assertBoard } from "./authz.js";
import { chatService } from "../services/chat.js";

/**
 * Build a summary string from user messages only, capped at 1500 chars.
 * Exported for unit testing.
 */
export function buildHandoffSummary(
  messages: Array<{ role: string; content: string }>,
): string {
  const userMessages = messages
    .filter((m) => m.role === "user")
    .map((m) => m.content)
    .join("\n");

  return userMessages.slice(0, 1500);
}

export function assistantHandoffRoutes(db: Db): Router {
  const router = Router();
  const svc = chatService(db);

  // POST /api/conversations/:id/assistant-handoff
  // Creates a new PM conversation with a handoff_context system message
  // containing a summary of user messages from the source conversation.
  router.post("/conversations/:id/assistant-handoff", async (req, res) => {
    assertBoard(req);

    // 1. Get source conversation
    const conversation = await svc.getConversation(req.params.id!);

    // 2. Fetch last 20 messages
    const msgs = await svc.listMessages(req.params.id!, { limit: 20 });

    // 3. Build summary from user messages only, capped at 1500 chars
    const summary = buildHandoffSummary(msgs.items);

    // 4. Create new PM conversation (generic — PM agent wiring is out of scope here)
    const newConv = await svc.createConversation(conversation.companyId, {
      title: "Project from assistant chat",
    });

    // 5. Insert handoff_context system message
    await svc.addSystemMessage(newConv.id, {
      content: summary,
      messageType: "handoff_context",
    });

    // 6. Return target conversation ID
    res.json({ targetConversationId: newConv.id });
  });

  return router;
}
