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 { AgentWithinContextOfProjectResponse, AgentWithinContextOfProjectSchema, ErrorResponseSchema, TenantProjectAgentParamsSchema, TenantProjectParamsSchema, commonGetErrorResponses, createApiError, createFullAgentServerSide, deleteFullAgent, getFullAgent, updateFullAgentServerSide } from "@inkeep/agents-core";
import { createProtectedRoute } from "@inkeep/agents-core/middleware";
import { HTTPException } from "hono/http-exception";
import { clearWorkspaceConnectionCache } from "@inkeep/agents-work-apps/slack";

//#region src/domains/manage/routes/agentFull.ts
const logger = getLogger$1("agentFull");
const app = new OpenAPIHono();
app.openapi(createProtectedRoute({
	method: "post",
	path: "/",
	permission: requireProjectPermission("edit"),
	summary: "Create Full Agent",
	operationId: "create-full-agent",
	tags: ["Agents"],
	description: "Create a complete agent with all agents, tools, and relationships from JSON definition",
	request: {
		params: TenantProjectParamsSchema,
		body: { content: { "application/json": { schema: AgentWithinContextOfProjectSchema } } }
	},
	responses: {
		201: {
			description: "Full agent created successfully",
			content: { "application/json": { schema: AgentWithinContextOfProjectResponse } }
		},
		409: {
			description: "Agent already exists",
			content: { "application/json": { schema: ErrorResponseSchema } }
		},
		...commonGetErrorResponses
	}
}), async (c) => {
	const db = c.get("db");
	const { tenantId, projectId } = c.req.valid("param");
	const agentData = c.req.valid("json");
	const validatedAgentData = AgentWithinContextOfProjectSchema.parse(agentData);
	const createdAgent = await createFullAgentServerSide(db)({
		tenantId,
		projectId
	}, validatedAgentData);
	return c.json({ data: createdAgent }, 201);
});
app.openapi(createProtectedRoute({
	method: "get",
	path: "/{agentId}",
	permission: requireProjectPermission("view"),
	summary: "Get Full Agent",
	operationId: "get-full-agent",
	tags: ["Agents"],
	description: "Retrieve a complete agent definition with all agents, tools, and relationships",
	request: { params: TenantProjectAgentParamsSchema },
	responses: {
		200: {
			description: "Full agent found",
			content: { "application/json": { schema: AgentWithinContextOfProjectResponse } }
		},
		...commonGetErrorResponses
	}
}), async (c) => {
	const db = c.get("db");
	const { tenantId, projectId, agentId } = c.req.valid("param");
	try {
		const agent = await getFullAgent(db, logger)({ scopes: {
			tenantId,
			projectId,
			agentId
		} });
		if (!agent) throw createApiError({
			code: "not_found",
			message: "Agent not found"
		});
		return c.json({ data: agent });
	} catch (error) {
		if (error instanceof HTTPException) throw error;
		if (error instanceof Error && error.message.includes("not found")) throw createApiError({
			code: "not_found",
			message: "Agent not found"
		});
		throw createApiError({
			code: "internal_server_error",
			message: "Failed to retrieve agent"
		});
	}
});
const updateFullAgentRouteConfig = {
	path: "/{agentId}",
	permission: requireProjectPermission("edit"),
	summary: "Update Full Agent",
	tags: ["Agents"],
	description: "Update or create a complete agent with all agents, tools, and relationships from JSON definition",
	request: {
		params: TenantProjectAgentParamsSchema,
		body: { content: { "application/json": { schema: AgentWithinContextOfProjectSchema } } }
	},
	responses: {
		200: {
			description: "Full agent updated successfully",
			content: { "application/json": { schema: AgentWithinContextOfProjectResponse } }
		},
		201: {
			description: "Full agent created successfully",
			content: { "application/json": { schema: AgentWithinContextOfProjectResponse } }
		},
		...commonGetErrorResponses
	}
};
const updateFullAgentHandler = async (c) => {
	const db = c.get("db");
	const { tenantId, projectId, agentId } = c.req.valid("param");
	const agentData = c.req.valid("json");
	try {
		const validatedAgentData = AgentWithinContextOfProjectSchema.parse(agentData);
		if (agentId !== validatedAgentData.id) throw createApiError({
			code: "bad_request",
			message: `Agent ID mismatch: expected ${agentId}, got ${validatedAgentData.id}`
		});
		const isCreate = !await getFullAgent(db, logger)({ scopes: {
			tenantId,
			projectId,
			agentId
		} });
		const updatedAgent = isCreate ? await createFullAgentServerSide(db)({
			tenantId,
			projectId
		}, validatedAgentData) : await updateFullAgentServerSide(db)({
			tenantId,
			projectId
		}, validatedAgentData);
		return c.json({ data: updatedAgent }, isCreate ? 201 : 200);
	} catch (error) {
		if (error instanceof HTTPException) throw error;
		if (error instanceof Error && error.message.includes("ID mismatch")) throw createApiError({
			code: "bad_request",
			message: error.message
		});
		throw createApiError({
			code: "internal_server_error",
			message: "Failed to update agent"
		});
	}
};
openapiRegisterPutPatchRoutesForLegacy(app, updateFullAgentRouteConfig, updateFullAgentHandler, {
	operationId: "update-full-agent",
	canonical: "put"
});
app.openapi(createProtectedRoute({
	method: "delete",
	path: "/{agentId}",
	permission: requireProjectPermission("edit"),
	summary: "Delete Full Agent",
	operationId: "delete-full-agent",
	tags: ["Agents"],
	description: "Delete a complete agent and cascade to all related entities (relationships, not other agents/tools)",
	request: { params: TenantProjectAgentParamsSchema },
	responses: {
		204: { description: "Agent deleted successfully" },
		...commonGetErrorResponses
	}
}), async (c) => {
	const db = c.get("db");
	const { tenantId, projectId, agentId } = c.req.valid("param");
	try {
		if (!await deleteFullAgent(db, logger)({ scopes: {
			tenantId,
			projectId,
			agentId
		} })) throw createApiError({
			code: "not_found",
			message: "Agent not found"
		});
		clearWorkspaceConnectionCache();
		return c.body(null, 204);
	} catch (error) {
		if (error instanceof HTTPException) throw error;
		if (error instanceof Error && error.message.includes("not found")) throw createApiError({
			code: "not_found",
			message: "Agent not found"
		});
		throw createApiError({
			code: "internal_server_error",
			message: "Failed to delete agent"
		});
	}
});
var agentFull_default = app;

//#endregion
export { agentFull_default as default };