import { Router } from "express";
import type { AppServices } from "../serverContext";
import type { AssistantMessageRequestPayload } from "../types/assistant";
import { ApiError, ok } from "../utils/http";

export function buildAssistantRouter(services: AppServices): Router {
  const router = Router();

  router.post("/api/assistant/message", async (req, res, next) => {
    try {
      const payload = (req.body ?? {}) as Partial<AssistantMessageRequestPayload>;
      const userMessageSource =
        typeof payload.user_message === "string"
          ? payload.user_message
          : typeof payload.message === "string"
            ? payload.message
            : "";
      const userMessage = userMessageSource.trim();
      if (!userMessage) {
        throw new ApiError("INVALID_ASSISTANT_MESSAGE", "Field `user_message` or `message` is required.", 400);
      }

      const response = await services.assistantService.handleMessage({
        ...payload,
        user_message: userMessage,
        message: userMessage,
        mode: typeof payload.mode === "string" ? payload.mode : "assistant"
      });
      ok(res, response);
    } catch (error) {
      next(error);
    }
  });

  router.get("/api/assistant/session/:session_id", (req, res, next) => {
    try {
      const sessionId = String(req.params.session_id ?? "");
      const session = services.assistantService.getSession(sessionId);
      if (!session) {
        throw new ApiError("ASSISTANT_SESSION_NOT_FOUND", `Session not found: ${sessionId}`, 404);
      }
      ok(res, {
        ok: true,
        session
      });
    } catch (error) {
      next(error);
    }
  });

  return router;
}
