import runDbClient_default from "../../../data/db/runDbClient.js";
import { requireProjectPermission } from "../../../middleware/projectAccess.js";
import { speakeasyOffsetLimitPagination } from "../../../utils/speakeasy.js";
import { OpenAPIHono, createRoute, z } from "@hono/zod-openapi";
import { ApiKeyApiCreationResponseSchema, ApiKeyApiInsertSchema, ApiKeyApiUpdateSchema, ApiKeyListResponse, ApiKeyResponse, ErrorResponseSchema, PaginationQueryParamsSchema, TenantProjectIdParamsSchema, TenantProjectParamsSchema, commonGetErrorResponses, createApiError, createApiKey, deleteApiKey, generateApiKey, getApiKeyById, listApiKeysPaginated, updateApiKey } from "@inkeep/agents-core";

//#region src/domains/manage/routes/apiKeys.ts
const app = new OpenAPIHono();
app.use("/", async (c, next) => {
	if (c.req.method === "POST") return requireProjectPermission("use")(c, next);
	return next();
});
app.use("/:id", async (c, next) => {
	if (c.req.method === "PUT" || c.req.method === "DELETE") return requireProjectPermission("edit")(c, next);
	return next();
});
app.openapi(createRoute({
	method: "get",
	path: "/",
	summary: "List API Keys",
	description: "List all API keys for a tenant with optional pagination",
	operationId: "list-api-keys",
	tags: ["API Keys"],
	request: {
		params: TenantProjectParamsSchema,
		query: PaginationQueryParamsSchema.extend({ agentId: z.string().optional().describe("Filter by agent ID") })
	},
	responses: {
		200: {
			description: "List of API keys retrieved successfully",
			content: { "application/json": { schema: ApiKeyListResponse } }
		},
		...commonGetErrorResponses
	},
	...speakeasyOffsetLimitPagination
}), async (c) => {
	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 agentId = c.req.query("agentId");
	const result = await listApiKeysPaginated(runDbClient_default)({
		scopes: {
			tenantId,
			projectId
		},
		pagination: {
			page,
			limit
		},
		agentId
	});
	const sanitizedData = result.data.map(({ keyHash, tenantId: tenantId$1, projectId: projectId$1, ...apiKey }) => apiKey);
	return c.json({
		data: sanitizedData,
		pagination: result.pagination
	});
});
app.openapi(createRoute({
	method: "get",
	path: "/{id}",
	summary: "Get API Key",
	description: "Get a specific API key by ID (does not return the actual key)",
	operationId: "get-api-key-by-id",
	tags: ["API Keys"],
	request: { params: TenantProjectIdParamsSchema },
	responses: {
		200: {
			description: "API key found",
			content: { "application/json": { schema: ApiKeyResponse } }
		},
		...commonGetErrorResponses
	}
}), async (c) => {
	const { tenantId, projectId, id } = c.req.valid("param");
	const apiKey = await getApiKeyById(runDbClient_default)({
		scopes: {
			tenantId,
			projectId
		},
		id
	});
	if (!apiKey || apiKey === void 0) throw createApiError({
		code: "not_found",
		message: "API key not found"
	});
	const { keyHash: _, tenantId: __, projectId: ___, ...sanitizedApiKey } = apiKey;
	return c.json({ data: {
		...sanitizedApiKey,
		lastUsedAt: sanitizedApiKey.lastUsedAt ?? null,
		expiresAt: sanitizedApiKey.expiresAt ?? null
	} });
});
app.openapi(createRoute({
	method: "post",
	path: "/",
	summary: "Create API Key",
	description: "Create a new API key for an agent. Returns the full key (shown only once).",
	operationId: "create-api-key",
	tags: ["API Keys"],
	request: {
		params: TenantProjectParamsSchema,
		body: { content: { "application/json": { schema: ApiKeyApiInsertSchema } } }
	},
	responses: {
		201: {
			description: "API key created successfully",
			content: { "application/json": { schema: ApiKeyApiCreationResponseSchema } }
		},
		...commonGetErrorResponses
	}
}), async (c) => {
	const { tenantId, projectId } = c.req.valid("param");
	const body = c.req.valid("json");
	const { key, ...keyDataWithoutKey } = await generateApiKey();
	const insertData = {
		tenantId,
		projectId,
		name: body.name,
		agentId: body.agentId,
		...keyDataWithoutKey,
		expiresAt: body.expiresAt || void 0
	};
	try {
		const { keyHash: _, tenantId: __, projectId: ___, ...sanitizedApiKey } = await createApiKey(runDbClient_default)(insertData);
		return c.json({ data: {
			apiKey: {
				...sanitizedApiKey,
				lastUsedAt: sanitizedApiKey.lastUsedAt ?? null,
				expiresAt: sanitizedApiKey.expiresAt ?? null
			},
			key
		} }, 201);
	} catch (error) {
		if (error?.cause?.code === "23503") throw createApiError({
			code: "bad_request",
			message: "Invalid agentId - agent does not exist"
		});
		throw error;
	}
});
app.openapi(createRoute({
	method: "put",
	path: "/{id}",
	summary: "Update API Key",
	description: "Update an API key (currently only expiration date can be changed)",
	operationId: "update-api-key",
	tags: ["API Keys"],
	request: {
		params: TenantProjectIdParamsSchema,
		body: { content: { "application/json": { schema: ApiKeyApiUpdateSchema } } }
	},
	responses: {
		200: {
			description: "API key updated successfully",
			content: { "application/json": { schema: ApiKeyResponse } }
		},
		...commonGetErrorResponses
	}
}), async (c) => {
	const { tenantId, projectId, id } = c.req.valid("param");
	const body = c.req.valid("json");
	const updatedApiKey = await updateApiKey(runDbClient_default)({
		scopes: {
			tenantId,
			projectId
		},
		id,
		data: {
			expiresAt: body.expiresAt,
			name: body.name
		}
	});
	if (!updatedApiKey) throw createApiError({
		code: "not_found",
		message: "API key not found"
	});
	const { keyHash: _, tenantId: __, projectId: ___, ...sanitizedApiKey } = updatedApiKey;
	return c.json({ data: {
		...sanitizedApiKey,
		lastUsedAt: sanitizedApiKey.lastUsedAt ?? null,
		expiresAt: sanitizedApiKey.expiresAt ?? null
	} });
});
app.openapi(createRoute({
	method: "delete",
	path: "/{id}",
	summary: "Delete API Key",
	description: "Delete an API key permanently",
	operationId: "delete-api-key",
	tags: ["API Keys"],
	request: { params: TenantProjectIdParamsSchema },
	responses: {
		204: { description: "API key deleted successfully" },
		404: {
			description: "API key not found",
			content: { "application/json": { schema: ErrorResponseSchema } }
		}
	}
}), async (c) => {
	const { tenantId, projectId, id } = c.req.valid("param");
	if (!await deleteApiKey(runDbClient_default)({
		scopes: {
			tenantId,
			projectId
		},
		id
	})) throw createApiError({
		code: "not_found",
		message: "API key not found"
	});
	return c.body(null, 204);
});
var apiKeys_default = app;

//#endregion
export { apiKeys_default as default };