import { requireProjectPermission } from "../../../middleware/projectAccess.js";
import { speakeasyOffsetLimitPagination } from "../../../utils/speakeasy.js";
import { OpenAPIHono, createRoute } from "@hono/zod-openapi";
import { ArtifactComponentApiInsertSchema, ArtifactComponentApiUpdateSchema, ArtifactComponentListResponse, ArtifactComponentResponse, ErrorResponseSchema, PaginationQueryParamsSchema, TenantProjectIdParamsSchema, TenantProjectParamsSchema, commonGetErrorResponses, createApiError, createArtifactComponent, deleteArtifactComponent, generateId, getArtifactComponentById, listArtifactComponentsPaginated, updateArtifactComponent, validatePropsAsJsonSchema } from "@inkeep/agents-core";

//#region src/domains/manage/routes/artifactComponents.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 === "PATCH" || 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 Artifact Components",
	operationId: "list-artifact-components",
	tags: ["Artifact Components"],
	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(createRoute({
	method: "get",
	path: "/{id}",
	summary: "Get Artifact Component",
	operationId: "get-artifact-component-by-id",
	tags: ["Artifact Components"],
	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(createRoute({
	method: "post",
	path: "/",
	summary: "Create Artifact Component",
	operationId: "create-artifact-component",
	tags: ["Artifact Components"],
	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 = {
		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) {
		if (error?.cause?.code === "23505") throw createApiError({
			code: "conflict",
			message: `Artifact component with ID '${finalId}' already exists`
		});
		throw error;
	}
});
app.openapi(createRoute({
	method: "put",
	path: "/{id}",
	summary: "Update Artifact Component",
	operationId: "update-artifact-component",
	tags: ["Artifact Components"],
	request: {
		params: TenantProjectIdParamsSchema,
		body: { content: { "application/json": { schema: ArtifactComponentApiUpdateSchema } } }
	},
	responses: {
		200: {
			description: "Artifact component updated successfully",
			content: { "application/json": { schema: ArtifactComponentResponse } }
		},
		...commonGetErrorResponses
	}
}), 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 = {};
	if (body.name !== void 0) updateData.name = String(body.name);
	if (body.description !== void 0) updateData.description = String(body.description);
	if (body.props !== void 0) updateData.props = body.props ?? null;
	if (body.render !== void 0) updateData.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 });
});
app.openapi(createRoute({
	method: "delete",
	path: "/{id}",
	summary: "Delete Artifact Component",
	operationId: "delete-artifact-component",
	tags: ["Artifact Components"],
	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 };