import runDbClient_default from "../../../data/db/runDbClient.js";
import { speakeasyOffsetLimitPagination } from "../../../utils/speakeasy.js";
import { OpenAPIHono, z } from "@hono/zod-openapi";
import { AppListResponse, OrgRoles, PaginationQueryParamsSchema, TenantParamsSchema, commonGetErrorResponses, listAppsPaginated, listUsableProjectIds, sanitizeAppConfig } from "@inkeep/agents-core";
import { createProtectedRoute, inheritedManageTenantAuth } from "@inkeep/agents-core/middleware";

//#region src/domains/manage/routes/tenantApps.ts
const app = new OpenAPIHono();
app.openapi(createProtectedRoute({
	method: "get",
	path: "/",
	summary: "List Tenant Apps",
	description: "List all apps for a tenant across all projects, optionally filtered by type",
	operationId: "list-tenant-apps",
	tags: ["Apps"],
	permission: inheritedManageTenantAuth(),
	request: {
		params: TenantParamsSchema,
		query: PaginationQueryParamsSchema.extend({ type: z.enum([
			"web_client",
			"api",
			"support_copilot"
		]).optional().describe("Filter by app type") })
	},
	responses: {
		200: {
			description: "List of apps retrieved successfully",
			content: { "application/json": { schema: AppListResponse } }
		},
		...commonGetErrorResponses
	},
	...speakeasyOffsetLimitPagination
}), async (c) => {
	const { tenantId } = c.req.valid("param");
	const userId = c.get("userId");
	const tenantRole = c.get("tenantRole");
	const page = Number(c.req.query("page")) || 1;
	const limit = Math.min(Number(c.req.query("limit")) || 10, 100);
	const type = c.req.query("type");
	const isOrgAdmin = tenantRole === OrgRoles.OWNER || tenantRole === OrgRoles.ADMIN;
	let projectIds;
	if (!isOrgAdmin) {
		projectIds = userId ? await listUsableProjectIds({
			userId,
			tenantId
		}) : [];
		if (projectIds.length === 0) {
			const tenantWide = await listAppsPaginated(runDbClient_default)({
				scopes: { tenantId },
				pagination: {
					page: 1,
					limit: 1
				},
				type
			});
			return c.json({
				data: [],
				pagination: {
					page,
					limit,
					total: 0,
					pages: 0
				},
				role: tenantRole,
				tenantHasAnyApps: tenantWide.pagination.total > 0
			});
		}
	}
	const result = await listAppsPaginated(runDbClient_default)({
		scopes: {
			tenantId,
			projectIds
		},
		pagination: {
			page,
			limit
		},
		type
	});
	const sanitizedData = result.data.map((app$1) => sanitizeAppConfig(app$1));
	let tenantHasAnyApps;
	if (result.pagination.total > 0) tenantHasAnyApps = true;
	else if (isOrgAdmin) tenantHasAnyApps = false;
	else tenantHasAnyApps = (await listAppsPaginated(runDbClient_default)({
		scopes: { tenantId },
		pagination: {
			page: 1,
			limit: 1
		},
		type
	})).pagination.total > 0;
	return c.json({
		data: sanitizedData,
		pagination: result.pagination,
		role: tenantRole,
		tenantHasAnyApps
	});
});
var tenantApps_default = app;

//#endregion
export { tenantApps_default as default };