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 { ArtifactComponentApiInsertSchema, ArtifactComponentApiUpdateSchema, ArtifactComponentListResponse, ArtifactComponentResponse, ErrorResponseSchema, PaginationQueryParamsSchema, TenantProjectIdParamsSchema, TenantProjectParamsSchema, commonGetErrorResponses, createApiError, createArtifactComponent, deleteArtifactComponent, generateId, getArtifactComponentById, listArtifactComponentsPaginated, throwIfUniqueConstraintError, updateArtifactComponent, validatePropsAsJsonSchema } from "@inkeep/agents-core";
import { createProtectedRoute } from "@inkeep/agents-core/middleware";

//#region src/domains/manage/routes/artifactComponents.ts
const app = new OpenAPIHono();
app.openapi(createProtectedRoute({
	method: "get",
	path: "/",
	summary: "List Artifact Components",
	operationId: "list-artifact-components",
	tags: ["Artifact Components"],
	permission: requireProjectPermission("view"),
	request: {
		params: TenantProjectParamsSchema,
		query: PaginationQueryParamsSchema
	},
	responses: {
		200: {
			description: "List of artifact components retrieved successfully",
			content: { "application/json": { schema: ArtifactComponentListResponse } }
		},
		...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);
	const result = await listArtifactComponentsPaginated(db)({
		scopes: {
			tenantId,
			projectId
		},
		pagination: {
			page,
			limit
		}
	});
	return c.json(result);
});
app.openapi(createProtectedRoute({
	method: "get",
	path: "/{id}",
	summary: "Get Artifact Component",
	operationId: "get-artifact-component-by-id",
	tags: ["Artifact Components"],
	permission: requireProjectPermission("view"),
	request: { params: TenantProjectIdParamsSchema },
	responses: {
		200: {
			description: "Artifact component found",
			content: { "application/json": { schema: ArtifactComponentResponse } }
		},
		...commonGetErrorResponses
	}
}), async (c) => {
	const db = c.get("db");
	const { tenantId, projectId, id } = c.req.valid("param");
	const artifactComponent = await getArtifactComponentById(db)({
		scopes: {
			tenantId,
			projectId
		},
		id
	});
	if (!artifactComponent) throw createApiError({
		code: "not_found",
		message: "Artifact component not found"
	});
	return c.json({ data: artifactComponent });
});
app.openapi(createProtectedRoute({
	method: "post",
	path: "/",
	summary: "Create Artifact Component",
	operationId: "create-artifact-component",
	tags: ["Artifact Components"],
	permission: requireProjectPermission("edit"),
	request: {
		params: TenantProjectParamsSchema,
		body: { content: { "application/json": { schema: ArtifactComponentApiInsertSchema } } }
	},
	responses: {
		201: {
			description: "Artifact component created successfully",
			content: { "application/json": { schema: ArtifactComponentResponse } }
		},
		...commonGetErrorResponses
	}
}), async (c) => {
	const db = c.get("db");
	const { tenantId, projectId } = c.req.valid("param");
	const body = c.req.valid("json");
	if (body.props !== null && body.props !== void 0) {
		const propsValidation = validatePropsAsJsonSchema(body.props);
		if (!propsValidation.isValid) throw createApiError({
			code: "bad_request",
			message: `Invalid props schema: ${propsValidation.errors.map((e) => `${e.field}: ${e.message}`).join(", ")}`
		});
	}
	const finalId = body.id ? String(body.id) : generateId();
	const componentData = {
		...body,
		tenantId,
		projectId,
		id: finalId,
		name: String(body.name),
		description: String(body.description),
		props: body.props ?? null,
		render: body.render ?? null
	};
	try {
		const artifactComponent = await createArtifactComponent(db)({ ...componentData });
		return c.json({ data: artifactComponent }, 201);
	} catch (error) {
		throwIfUniqueConstraintError(error, `Artifact component with ID '${finalId}' already exists`);
		throw error;
	}
});
const updateArtifactComponentRouteConfig = {
	path: "/{id}",
	summary: "Update Artifact Component",
	tags: ["Artifact Components"],
	permission: requireProjectPermission("edit"),
	request: {
		params: TenantProjectIdParamsSchema,
		body: { content: { "application/json": { schema: ArtifactComponentApiUpdateSchema } } }
	},
	responses: {
		200: {
			description: "Artifact component updated successfully",
			content: { "application/json": { schema: ArtifactComponentResponse } }
		},
		...commonGetErrorResponses
	}
};
const updateArtifactComponentHandler = async (c) => {
	const db = c.get("db");
	const { tenantId, projectId, id } = c.req.valid("param");
	const body = c.req.valid("json");
	if (body.props !== void 0 && body.props !== null) {
		const propsValidation = validatePropsAsJsonSchema(body.props);
		if (!propsValidation.isValid) throw createApiError({
			code: "bad_request",
			message: `Invalid props schema: ${propsValidation.errors.map((e) => `${e.field}: ${e.message}`).join(", ")}`
		});
	}
	const updateData = {
		...body,
		...body.name !== void 0 && { name: String(body.name) },
		...body.description !== void 0 && { description: String(body.description) },
		...body.props !== void 0 && { props: body.props ?? null },
		...body.render !== void 0 && { render: body.render ?? null }
	};
	const updatedArtifactComponent = await updateArtifactComponent(db)({
		scopes: {
			tenantId,
			projectId
		},
		id,
		data: updateData
	});
	if (!updatedArtifactComponent) throw createApiError({
		code: "not_found",
		message: "Artifact component not found"
	});
	return c.json({ data: updatedArtifactComponent });
};
openapiRegisterPutPatchRoutesForLegacy(app, updateArtifactComponentRouteConfig, updateArtifactComponentHandler, { operationId: "update-artifact-component" });
app.openapi(createProtectedRoute({
	method: "delete",
	path: "/{id}",
	summary: "Delete Artifact Component",
	operationId: "delete-artifact-component",
	tags: ["Artifact Components"],
	permission: requireProjectPermission("edit"),
	request: { params: TenantProjectIdParamsSchema },
	responses: {
		204: { description: "Artifact component deleted successfully" },
		404: {
			description: "Artifact component not found",
			content: { "application/json": { schema: ErrorResponseSchema } }
		}
	}
}), async (c) => {
	const db = c.get("db");
	const { tenantId, projectId, id } = c.req.valid("param");
	if (!await deleteArtifactComponent(db)({
		scopes: {
			tenantId,
			projectId
		},
		id
	})) throw createApiError({
		code: "not_found",
		message: "Artifact component not found"
	});
	return c.body(null, 204);
});
var artifactComponents_default = app;

//#endregion
export { artifactComponents_default as default };