import { getLogger as getLogger$1 } from "../../../logger.js";
import { requireProjectPermission } from "../../../middleware/projectAccess.js";
import { openapiRegisterPutPatchRoutesForLegacy } from "../../../utils/openapiDualRoute.js";
import { speakeasyOffsetLimitPagination } from "../../../utils/speakeasy.js";
import { OpenAPIHono } from "@hono/zod-openapi";
import { FunctionApiInsertSchema, FunctionApiUpdateSchema, FunctionListResponse, FunctionResponse, PaginationQueryParamsSchema, TenantProjectIdParamsSchema, TenantProjectParamsSchema, commonGetErrorResponses, createApiError, deleteFunction, generateId, getFunction, listFunctionsPaginated, upsertFunction } from "@inkeep/agents-core";
import { createProtectedRoute } from "@inkeep/agents-core/middleware";

//#region src/domains/manage/routes/functions.ts
const logger = getLogger$1("functions");
const app = new OpenAPIHono();
app.openapi(createProtectedRoute({
	method: "get",
	path: "/",
	summary: "List Functions",
	operationId: "list-functions",
	tags: ["Functions"],
	permission: requireProjectPermission("view"),
	request: {
		params: TenantProjectParamsSchema,
		query: PaginationQueryParamsSchema
	},
	responses: {
		200: {
			description: "List of functions",
			content: { "application/json": { schema: FunctionListResponse } }
		},
		...commonGetErrorResponses
	},
	...speakeasyOffsetLimitPagination
}), async (c) => {
	const db = c.get("db");
	const { tenantId, projectId } = c.req.valid("param");
	const page = Number(c.req.query("page")) || 1;
	const limit = Math.min(Number(c.req.query("limit")) || 10, 100);
	try {
		const result = await listFunctionsPaginated(db)({
			scopes: {
				tenantId,
				projectId
			},
			pagination: {
				page,
				limit
			}
		});
		return c.json(result);
	} catch (error) {
		logger.error({
			error,
			tenantId
		}, "Failed to list functions");
		return c.json(createApiError({
			code: "internal_server_error",
			message: "Failed to list functions"
		}), 500);
	}
});
app.openapi(createProtectedRoute({
	method: "get",
	path: "/{id}",
	permission: requireProjectPermission("view"),
	summary: "Get Function by ID",
	operationId: "get-function",
	tags: ["Functions"],
	request: { params: TenantProjectIdParamsSchema },
	responses: {
		200: {
			description: "Function details",
			content: { "application/json": { schema: FunctionResponse } }
		},
		...commonGetErrorResponses
	}
}), async (c) => {
	const db = c.get("db");
	const { tenantId, projectId, id } = c.req.valid("param");
	try {
		const functionData = await getFunction(db)({
			functionId: id,
			scopes: {
				tenantId,
				projectId
			}
		});
		if (!functionData) return c.json(createApiError({
			code: "not_found",
			message: "Function not found"
		}), 404);
		return c.json({ data: functionData });
	} catch (error) {
		logger.error({
			error,
			tenantId,
			id
		}, "Failed to get function");
		return c.json(createApiError({
			code: "internal_server_error",
			message: "Failed to get function"
		}), 500);
	}
});
app.openapi(createProtectedRoute({
	method: "post",
	path: "/",
	permission: requireProjectPermission("edit"),
	summary: "Create Function",
	operationId: "create-function",
	tags: ["Functions"],
	request: {
		params: TenantProjectParamsSchema,
		body: { content: { "application/json": { schema: FunctionApiInsertSchema } } }
	},
	responses: {
		201: {
			description: "Function created",
			content: { "application/json": { schema: FunctionResponse } }
		},
		...commonGetErrorResponses
	}
}), async (c) => {
	const db = c.get("db");
	const { tenantId, projectId } = c.req.valid("param");
	const functionData = c.req.valid("json");
	try {
		const id = functionData.id || generateId();
		await upsertFunction(db)({
			data: {
				...functionData,
				id
			},
			scopes: {
				tenantId,
				projectId
			}
		});
		const created = await getFunction(db)({
			functionId: id,
			scopes: {
				tenantId,
				projectId
			}
		});
		logger.info({
			tenantId,
			functionId: id
		}, "Function created");
		return c.json({ data: created }, 201);
	} catch (error) {
		logger.error({
			error,
			tenantId,
			functionData
		}, "Failed to create function");
		return c.json(createApiError({
			code: "internal_server_error",
			message: "Failed to create function"
		}), 500);
	}
});
const updateFunctionRouteConfig = {
	path: "/{id}",
	permission: requireProjectPermission("edit"),
	summary: "Update Function",
	tags: ["Functions"],
	request: {
		params: TenantProjectIdParamsSchema,
		body: { content: { "application/json": { schema: FunctionApiUpdateSchema } } }
	},
	responses: {
		200: {
			description: "Function updated",
			content: { "application/json": { schema: FunctionResponse } }
		},
		...commonGetErrorResponses
	}
};
const updateFunctionHandler = async (c) => {
	const db = c.get("db");
	const { tenantId, projectId, id } = c.req.valid("param");
	const updateData = c.req.valid("json");
	try {
		const existing = await getFunction(db)({
			functionId: id,
			scopes: {
				tenantId,
				projectId
			}
		});
		if (!existing) return c.json(createApiError({
			code: "not_found",
			message: "Function not found"
		}), 404);
		await upsertFunction(db)({
			data: {
				...existing,
				...updateData,
				id
			},
			scopes: {
				tenantId,
				projectId
			}
		});
		const updated = await getFunction(db)({
			functionId: id,
			scopes: {
				tenantId,
				projectId
			}
		});
		logger.info({
			tenantId,
			functionId: id
		}, "Function updated");
		return c.json({ data: updated });
	} catch (error) {
		logger.error({
			error,
			tenantId,
			id,
			updateData
		}, "Failed to update function");
		return c.json(createApiError({
			code: "internal_server_error",
			message: "Failed to update function"
		}), 500);
	}
};
openapiRegisterPutPatchRoutesForLegacy(app, updateFunctionRouteConfig, updateFunctionHandler, { operationId: "update-function" });
app.openapi(createProtectedRoute({
	method: "delete",
	path: "/{id}",
	permission: requireProjectPermission("edit"),
	summary: "Delete Function",
	operationId: "delete-function",
	tags: ["Functions"],
	request: { params: TenantProjectIdParamsSchema },
	responses: {
		204: { description: "Function deleted" },
		...commonGetErrorResponses
	}
}), async (c) => {
	const db = c.get("db");
	const { tenantId, projectId, id } = c.req.valid("param");
	try {
		if (!await getFunction(db)({
			functionId: id,
			scopes: {
				tenantId,
				projectId
			}
		})) return c.json(createApiError({
			code: "not_found",
			message: "Function not found"
		}), 404);
		await deleteFunction(db)({
			functionId: id,
			scopes: {
				tenantId,
				projectId
			}
		});
		logger.info({
			tenantId,
			functionId: id
		}, "Function deleted");
		return c.body(null, 204);
	} catch (error) {
		logger.error({
			error,
			tenantId,
			id
		}, "Failed to delete function");
		return c.json(createApiError({
			code: "internal_server_error",
			message: "Failed to delete function"
		}), 500);
	}
});
var functions_default = app;

//#endregion
export { functions_default as default };