import runDbClient_default from "../../../data/db/runDbClient.js";
import { getLogger as getLogger$1 } from "../../../logger.js";
import { requireProjectPermission } from "../../../middleware/projectAccess.js";
import { openapiRegisterPutPatchRoutesForLegacy } from "../../../utils/openapiDualRoute.js";
import { OpenAPIHono } from "@hono/zod-openapi";
import { TenantProjectToolParamsSchema, WorkAppSlackMcpToolAccessConfigApiInsertSchema, commonGetErrorResponses, commonUpdateErrorResponses, createApiError, getSlackMcpToolAccessConfig, getToolById, setSlackMcpToolAccessConfig } from "@inkeep/agents-core";
import { createProtectedRoute } from "@inkeep/agents-core/middleware";
import { getSlackClient, resolveWorkspaceToken, validateBotChannelMembership } from "@inkeep/agents-work-apps/slack";

//#region src/domains/manage/routes/mcpToolSlackAccess.ts
const logger = getLogger$1("mcp-tool-slack-access");
const app = new OpenAPIHono();
async function validateSlackWorkappTool(db, tenantId, projectId, toolId) {
	const tool = await getToolById(db)({
		scopes: {
			tenantId,
			projectId
		},
		toolId
	});
	if (!tool) throw createApiError({
		code: "not_found",
		message: `Tool not found: ${toolId}`
	});
	if (!tool.isWorkApp) throw createApiError({
		code: "bad_request",
		message: "Slack access can only be configured for workapp MCP tools"
	});
	if (!tool.config.mcp.server.url?.includes("/slack/mcp")) throw createApiError({
		code: "bad_request",
		message: "Slack access can only be configured for Slack MCP tools"
	});
}
app.openapi(createProtectedRoute({
	method: "get",
	path: "/",
	summary: "Get MCP tool Slack channel access",
	operationId: "get-mcp-tool-slack-access",
	tags: ["Tools"],
	description: "Returns the current Slack channel access configuration for an MCP tool. If channelAccessMode is \"all\", the tool can post to any channel. If channelAccessMode is \"selected\", the tool is scoped to specific channels.",
	permission: requireProjectPermission("view"),
	request: { params: TenantProjectToolParamsSchema },
	responses: {
		200: {
			description: "Slack access configuration retrieved successfully",
			content: { "application/json": { schema: WorkAppSlackMcpToolAccessConfigApiInsertSchema } }
		},
		...commonGetErrorResponses
	}
}), async (c) => {
	const { tenantId, projectId, toolId } = c.req.valid("param");
	const db = c.get("db");
	logger.info({
		tenantId,
		projectId,
		toolId
	}, "Getting MCP tool Slack access configuration");
	await validateSlackWorkappTool(db, tenantId, projectId, toolId);
	const config = await getSlackMcpToolAccessConfig(runDbClient_default)({
		tenantId,
		projectId,
		toolId
	});
	return c.json({
		channelAccessMode: config.channelAccessMode,
		dmEnabled: config.dmEnabled,
		channelIds: config.channelIds
	}, 200);
});
const setMcpToolSlackAccessRouteConfig = {
	path: "/",
	summary: "Set MCP tool Slack channel access",
	tags: ["Tools"],
	description: "Configures which Slack channels an MCP tool can post to. When channelAccessMode is \"all\", the tool can post to any channel. When channelAccessMode is \"selected\", the tool is scoped to specific channels (channelIds required).",
	permission: requireProjectPermission("edit"),
	request: {
		params: TenantProjectToolParamsSchema,
		body: { content: { "application/json": { schema: WorkAppSlackMcpToolAccessConfigApiInsertSchema } } }
	},
	responses: {
		200: {
			description: "Slack access configuration updated successfully",
			content: { "application/json": { schema: WorkAppSlackMcpToolAccessConfigApiInsertSchema } }
		},
		...commonUpdateErrorResponses
	}
};
const setMcpToolSlackAccessHandler = async (c) => {
	const { tenantId, projectId, toolId } = c.req.valid("param");
	const { channelAccessMode, dmEnabled, channelIds } = c.req.valid("json");
	const db = c.get("db");
	logger.info({
		tenantId,
		projectId,
		toolId,
		channelAccessMode
	}, "Setting MCP tool Slack access configuration");
	await validateSlackWorkappTool(db, tenantId, projectId, toolId);
	if (channelAccessMode === "selected") {
		if (!channelIds || channelIds.length === 0) throw createApiError({
			code: "bad_request",
			message: "channelIds is required when channelAccessMode is \"selected\""
		});
		const { invalid } = await validateBotChannelMembership(getSlackClient(await resolveWorkspaceToken(tenantId)), channelIds);
		if (invalid.length > 0) throw createApiError({
			code: "bad_request",
			message: `Bot is not a member of channels: ${invalid.join(", ")}`
		});
		await setSlackMcpToolAccessConfig(runDbClient_default)({
			toolId,
			tenantId,
			projectId,
			channelAccessMode: "selected",
			dmEnabled,
			channelIds
		});
		logger.info({
			tenantId,
			projectId,
			toolId,
			channelCount: channelIds.length
		}, "MCP tool Slack access set to selected channels");
		return c.json({
			channelAccessMode: "selected",
			dmEnabled,
			channelIds
		}, 200);
	}
	await setSlackMcpToolAccessConfig(runDbClient_default)({
		toolId,
		tenantId,
		projectId,
		channelAccessMode: "all",
		dmEnabled,
		channelIds: []
	});
	logger.info({
		tenantId,
		projectId,
		toolId
	}, "MCP tool Slack access set to all channels");
	return c.json({
		channelAccessMode: "all",
		dmEnabled,
		channelIds: []
	}, 200);
};
openapiRegisterPutPatchRoutesForLegacy(app, setMcpToolSlackAccessRouteConfig, setMcpToolSlackAccessHandler, {
	operationId: "set-mcp-tool-slack-access",
	canonical: "put"
});
var mcpToolSlackAccess_default = app;

//#endregion
export { mcpToolSlackAccess_default as default };