import runDbClient_default from "../../../data/db/runDbClient.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 { ContextConfigApiInsertSchema, ContextConfigApiUpdateSchema, ContextConfigListResponse, ContextConfigResponse, PaginationQueryParamsSchema, TenantProjectAgentIdParamsSchema, TenantProjectAgentParamsSchema, cascadeDeleteByContextConfig, commonDeleteErrorResponses, commonGetErrorResponses, commonUpdateErrorResponses, createApiError, createContextConfig, deleteContextConfig, getContextConfigById, listContextConfigsPaginated, updateContextConfig } from "@inkeep/agents-core";
import { createProtectedRoute } from "@inkeep/agents-core/middleware";

//#region src/domains/manage/routes/contextConfigs.ts
const app = new OpenAPIHono();
app.openapi(createProtectedRoute({
	method: "get",
	path: "/",
	summary: "List Context Configurations",
	operationId: "list-context-configs",
	tags: ["Context Configs"],
	permission: requireProjectPermission("view"),
	request: {
		params: TenantProjectAgentParamsSchema,
		query: PaginationQueryParamsSchema
	},
	responses: {
		200: {
			description: "List of context configurations retrieved successfully",
			content: { "application/json": { schema: ContextConfigListResponse } }
		},
		...commonGetErrorResponses
	},
	...speakeasyOffsetLimitPagination
}), async (c) => {
	const db = c.get("db");
	const { tenantId, projectId, agentId } = c.req.valid("param");
	const page = Number(c.req.query("page")) || 1;
	const limit = Math.min(Number(c.req.query("limit")) || 10, 100);
	const result = await listContextConfigsPaginated(db)({
		scopes: {
			tenantId,
			projectId,
			agentId
		},
		pagination: {
			page,
			limit
		}
	});
	return c.json(result);
});
app.openapi(createProtectedRoute({
	method: "get",
	path: "/{id}",
	summary: "Get Context Configuration",
	operationId: "get-context-config-by-id",
	tags: ["Context Configs"],
	permission: requireProjectPermission("view"),
	request: { params: TenantProjectAgentIdParamsSchema },
	responses: {
		200: {
			description: "Context configuration found",
			content: { "application/json": { schema: ContextConfigResponse } }
		},
		...commonGetErrorResponses
	}
}), async (c) => {
	const db = c.get("db");
	const { tenantId, projectId, agentId, id } = c.req.valid("param");
	const contextConfig = await getContextConfigById(db)({
		scopes: {
			tenantId,
			projectId,
			agentId
		},
		id
	});
	if (!contextConfig) throw createApiError({
		code: "not_found",
		message: "Context configuration not found"
	});
	return c.json({ data: contextConfig });
});
app.openapi(createProtectedRoute({
	method: "post",
	path: "/",
	summary: "Create Context Configuration",
	operationId: "create-context-config",
	tags: ["Context Configs"],
	permission: requireProjectPermission("edit"),
	request: {
		params: TenantProjectAgentParamsSchema,
		body: { content: { "application/json": { schema: ContextConfigApiInsertSchema } } }
	},
	responses: {
		201: {
			description: "Context configuration created successfully",
			content: { "application/json": { schema: ContextConfigResponse } }
		},
		...commonGetErrorResponses
	}
}), async (c) => {
	const db = c.get("db");
	const { tenantId, projectId, agentId } = c.req.valid("param");
	const configData = {
		tenantId,
		projectId,
		agentId,
		...c.req.valid("json")
	};
	const contextConfig = await createContextConfig(db)(configData);
	return c.json({ data: contextConfig }, 201);
});
const updateContextConfigRouteConfig = {
	path: "/{id}",
	summary: "Update Context Configuration",
	tags: ["Context Configs"],
	permission: requireProjectPermission("edit"),
	request: {
		params: TenantProjectAgentIdParamsSchema,
		body: { content: { "application/json": { schema: ContextConfigApiUpdateSchema } } }
	},
	responses: {
		200: {
			description: "Context configuration updated successfully",
			content: { "application/json": { schema: ContextConfigResponse } }
		},
		...commonUpdateErrorResponses
	}
};
const updateContextConfigHandler = async (c) => {
	const db = c.get("db");
	const { tenantId, projectId, agentId, id } = c.req.valid("param");
	const body = c.req.valid("json");
	const updatedContextConfig = await updateContextConfig(db)({
		scopes: {
			tenantId,
			projectId,
			agentId
		},
		id,
		data: body
	});
	if (!updatedContextConfig) throw createApiError({
		code: "not_found",
		message: "Context configuration not found"
	});
	return c.json({ data: updatedContextConfig });
};
openapiRegisterPutPatchRoutesForLegacy(app, updateContextConfigRouteConfig, updateContextConfigHandler, { operationId: "update-context-config" });
app.openapi(createProtectedRoute({
	method: "delete",
	path: "/{id}",
	summary: "Delete Context Configuration",
	operationId: "delete-context-config",
	tags: ["Context Configs"],
	permission: requireProjectPermission("edit"),
	request: { params: TenantProjectAgentIdParamsSchema },
	responses: {
		204: { description: "Context configuration deleted successfully" },
		...commonDeleteErrorResponses
	}
}), async (c) => {
	const db = c.get("db");
	const resolvedRef = c.get("resolvedRef");
	const { tenantId, projectId, agentId, id } = c.req.valid("param");
	await cascadeDeleteByContextConfig(runDbClient_default)({
		scopes: {
			tenantId,
			projectId
		},
		contextConfigId: id,
		fullBranchName: resolvedRef.name
	});
	if (!await deleteContextConfig(db)({
		scopes: {
			tenantId,
			projectId,
			agentId
		},
		id
	})) throw createApiError({
		code: "not_found",
		message: "Context configuration not found"
	});
	return c.body(null, 204);
});
var contextConfigs_default = app;

//#endregion
export { contextConfigs_default as default };