import { NextResponse } from "next/server";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { executeTool } from "../../../lib/tool-executor.js";
import { loadAllModuleTools } from "../../../lib/tool-loader.js";
const openApi = {
  tag: "AI Assistant",
  summary: "Execute AI tool",
  methods: {
    POST: { summary: "Execute a specific MCP tool by name" }
  }
};
const metadata = {
  POST: { requireAuth: true, requireFeatures: ["ai_assistant.view"] }
};
async function POST(req) {
  const auth = await getAuthFromRequest(req);
  if (!auth) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  try {
    const body = await req.json();
    const { toolName, args = {} } = body;
    if (!toolName || typeof toolName !== "string") {
      return NextResponse.json({ error: "toolName is required" }, { status: 400 });
    }
    const container = await createRequestContainer();
    const rbacService = container.resolve("rbacService");
    const acl = await rbacService.loadAcl(auth.sub, {
      tenantId: auth.tenantId,
      organizationId: auth.orgId
    });
    await loadAllModuleTools();
    const toolContext = {
      tenantId: auth.tenantId,
      organizationId: auth.orgId,
      userId: auth.sub,
      container,
      userFeatures: acl.features,
      isSuperAdmin: acl.isSuperAdmin
    };
    const result = await executeTool(toolName, args, toolContext);
    if (!result.success) {
      return NextResponse.json(
        { success: false, error: result.error },
        { status: result.errorCode === "UNAUTHORIZED" ? 403 : 400 }
      );
    }
    return NextResponse.json({
      success: true,
      result: result.result
    });
  } catch (error) {
    console.error("[AI Tools] Error executing tool:", error);
    return NextResponse.json(
      { success: false, error: "Tool execution failed" },
      { status: 500 }
    );
  }
}
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
