import { requireProjectPermission } from "../../../middleware/projectAccess.js";
import { OpenAPIHono, createRoute } from "@hono/zod-openapi";
import { CreateCredentialInStoreRequestSchema, CreateCredentialInStoreResponseSchema, CredentialStoreListResponseSchema, TenantProjectIdParamsSchema, TenantProjectParamsSchema, commonGetErrorResponses, createApiError } from "@inkeep/agents-core";

//#region src/domains/manage/routes/credentialStores.ts
const app = new OpenAPIHono();
app.use("/:id/credentials", async (c, next) => {
	if (c.req.method === "POST") return requireProjectPermission("edit")(c, next);
	return next();
});
app.openapi(createRoute({
	method: "get",
	path: "/",
	summary: "List Credential Stores",
	operationId: "list-credential-stores",
	tags: ["Credential Stores"],
	request: { params: TenantProjectParamsSchema },
	responses: {
		200: {
			description: "List of credential stores retrieved successfully",
			content: { "application/json": { schema: CredentialStoreListResponseSchema } }
		},
		...commonGetErrorResponses
	}
}), async (c) => {
	const allStores = c.get("credentialStores").getAll();
	const storeStatuses = await Promise.all(allStores.map(async (store) => {
		const { available, reason } = await store.checkAvailability();
		return {
			id: store.id,
			type: store.type,
			available,
			reason: reason || null
		};
	}));
	return c.json({ data: storeStatuses });
});
app.openapi(createRoute({
	method: "post",
	path: "/{id}/credentials",
	summary: "Create Credential in Store",
	operationId: "create-credential-in-store",
	tags: ["Credential Stores"],
	request: {
		params: TenantProjectIdParamsSchema,
		body: { content: { "application/json": { schema: CreateCredentialInStoreRequestSchema } } }
	},
	responses: {
		201: {
			description: "Credential created successfully",
			content: { "application/json": { schema: CreateCredentialInStoreResponseSchema } }
		},
		...commonGetErrorResponses
	}
}), async (c) => {
	const { id: storeId } = c.req.param();
	const { key, value, metadata } = await c.req.json();
	const store = c.get("credentialStores").get(storeId);
	if (!store) throw createApiError({
		code: "not_found",
		message: `Credential store '${storeId}' not found`
	});
	try {
		const { available, reason } = await store.checkAvailability();
		if (!available) throw createApiError({
			code: "internal_server_error",
			message: `Credential store '${storeId}' is not available: ${reason}`
		});
		await store.set(key, value, metadata ?? {});
		return c.json({ data: {
			key,
			storeId,
			createdAt: (/* @__PURE__ */ new Date()).toISOString()
		} }, 201);
	} catch (error) {
		console.error(`Error setting credential in store ${storeId}:`, error);
		throw createApiError({
			code: "internal_server_error",
			message: `Failed to store credential: ${error instanceof Error ? error.message : "Unknown error"}`
		});
	}
});
var credentialStores_default = app;

//#endregion
export { credentialStores_default as default };