import runDbClient_default from "../../../data/db/runDbClient.js";
import { requireProjectPermission } from "../../../middleware/projectAccess.js";
import { speakeasyOffsetLimitPagination } from "../../../utils/speakeasy.js";
import { OpenAPIHono, createRoute } from "@hono/zod-openapi";
import { ErrorResponseSchema, PaginationQueryParamsSchema, SubAgentApiInsertSchema, SubAgentApiUpdateSchema, SubAgentIsDefaultError, SubAgentListResponse, SubAgentResponse, TenantProjectAgentIdParamsSchema, TenantProjectAgentParamsSchema, cascadeDeleteBySubAgent, commonGetErrorResponses, createApiError, createSubAgent, deleteSubAgent, generateId, getSubAgentById, listSubAgentsPaginated, updateSubAgent } from "@inkeep/agents-core";

//#region src/domains/manage/routes/subAgents.ts
const app = new OpenAPIHono();
app.use("/", async (c, next) => {
	if (c.req.method === "POST") return requireProjectPermission("edit")(c, next);
	return next();
});
app.use("/:id", async (c, next) => {
	if (c.req.method === "PUT") return requireProjectPermission("edit")(c, next);
	if (c.req.method === "DELETE") return requireProjectPermission("edit")(c, next);
	return next();
});
app.openapi(createRoute({
	method: "get",
	path: "/",
	summary: "List SubAgents",
	operationId: "list-subagents",
	tags: ["SubAgents"],
	request: {
		params: TenantProjectAgentParamsSchema,
		query: PaginationQueryParamsSchema
	},
	responses: {
		200: {
			description: "List of subAgents retrieved successfully",
			content: { "application/json": { schema: SubAgentListResponse } }
		},
		...commonGetErrorResponses
	},
	...speakeasyOffsetLimitPagination
}), async (c) => {
	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 listSubAgentsPaginated(c.get("db"))({
		scopes: {
			tenantId,
			projectId,
			agentId
		},
		pagination: {
			page,
			limit
		}
	});
	const dataWithType = {
		...result,
		data: result.data.map((subAgent) => ({
			...subAgent,
			type: "internal"
		}))
	};
	return c.json(dataWithType);
});
app.openapi(createRoute({
	method: "get",
	path: "/{id}",
	summary: "Get SubAgent",
	operationId: "get-subagent-by-id",
	tags: ["SubAgents"],
	request: { params: TenantProjectAgentIdParamsSchema },
	responses: {
		200: {
			description: "SubAgent found",
			content: { "application/json": { schema: SubAgentResponse } }
		},
		...commonGetErrorResponses
	}
}), async (c) => {
	const { tenantId, projectId, agentId, id } = c.req.valid("param");
	const subAgent = await getSubAgentById(c.get("db"))({
		scopes: {
			tenantId,
			projectId,
			agentId
		},
		subAgentId: id
	});
	if (!subAgent) throw createApiError({
		code: "not_found",
		message: "SubAgent not found"
	});
	const subAgentWithType = {
		...subAgent,
		type: "internal"
	};
	return c.json({ data: subAgentWithType });
});
app.openapi(createRoute({
	method: "post",
	path: "/",
	summary: "Create SubAgent",
	operationId: "create-subagent",
	tags: ["SubAgents"],
	request: {
		params: TenantProjectAgentParamsSchema,
		body: { content: { "application/json": { schema: SubAgentApiInsertSchema } } }
	},
	responses: {
		201: {
			description: "SubAgent created successfully",
			content: { "application/json": { schema: SubAgentResponse } }
		},
		...commonGetErrorResponses
	}
}), async (c) => {
	const { tenantId, projectId, agentId } = c.req.valid("param");
	const body = c.req.valid("json");
	const subAgentId = body.id ? String(body.id) : generateId();
	const subAgentWithType = {
		...await createSubAgent(c.get("db"))({
			...body,
			id: subAgentId,
			tenantId,
			projectId,
			agentId
		}),
		type: "internal"
	};
	return c.json({ data: subAgentWithType }, 201);
});
app.openapi(createRoute({
	method: "put",
	path: "/{id}",
	summary: "Update SubAgent",
	operationId: "update-subagent",
	tags: ["SubAgents"],
	request: {
		params: TenantProjectAgentIdParamsSchema,
		body: { content: { "application/json": { schema: SubAgentApiUpdateSchema } } }
	},
	responses: {
		200: {
			description: "SubAgent updated successfully",
			content: { "application/json": { schema: SubAgentResponse } }
		},
		...commonGetErrorResponses
	}
}), async (c) => {
	const { tenantId, projectId, agentId, id } = c.req.valid("param");
	const body = c.req.valid("json");
	const updatedSubAgent = await updateSubAgent(c.get("db"))({
		scopes: {
			tenantId,
			projectId,
			agentId
		},
		subAgentId: id,
		data: body
	});
	if (!updatedSubAgent) throw createApiError({
		code: "not_found",
		message: "SubAgent not found"
	});
	const subAgentWithType = {
		...updatedSubAgent,
		type: "internal"
	};
	return c.json({ data: subAgentWithType });
});
app.openapi(createRoute({
	method: "delete",
	path: "/{id}",
	summary: "Delete SubAgent",
	operationId: "delete-subagent",
	tags: ["SubAgents"],
	request: { params: TenantProjectAgentIdParamsSchema },
	responses: {
		204: { description: "SubAgent deleted successfully" },
		404: {
			description: "SubAgent not found",
			content: { "application/json": { schema: ErrorResponseSchema } }
		},
		409: {
			description: "SubAgent is set as default and cannot be deleted",
			content: { "application/json": { schema: ErrorResponseSchema } }
		}
	}
}), async (c) => {
	const { tenantId, projectId, agentId, id } = c.req.valid("param");
	const db = c.get("db");
	const resolvedRef = c.get("resolvedRef");
	try {
		await cascadeDeleteBySubAgent(runDbClient_default)({
			scopes: {
				tenantId,
				projectId
			},
			subAgentId: id,
			fullBranchName: resolvedRef.name
		});
		if (!await deleteSubAgent(db)({
			scopes: {
				tenantId,
				projectId,
				agentId
			},
			subAgentId: id
		})) throw createApiError({
			code: "not_found",
			message: "SubAgent not found"
		});
		return c.body(null, 204);
	} catch (error) {
		if (error instanceof SubAgentIsDefaultError) throw createApiError({
			code: "conflict",
			message: error.message
		});
		throw error;
	}
});
var subAgents_default = app;

//#endregion
export { subAgents_default as default };