import { workAppGitHubInstallations, workAppGitHubMcpToolAccessMode, workAppGitHubMcpToolRepositoryAccess, workAppGitHubProjectAccessMode, workAppGitHubProjectRepositoryAccess, workAppGitHubRepositories } from "../../db/runtime/runtime-schema.js";
import { generateId } from "../../utils/conversations.js";
import { projectScopedWhere, tenantScopedWhere, toolScopedWhere } from "../manage/scope-helpers.js";
import { and, count, desc, eq, inArray, ne } from "drizzle-orm";

//#region src/data-access/runtime/github-work-app-installations.ts
/**
* Create a new GitHub App installation record
*/
const createInstallation = (db) => async (input) => {
	const now = (/* @__PURE__ */ new Date()).toISOString();
	const [created] = await db.insert(workAppGitHubInstallations).values({
		...input,
		createdAt: now,
		updatedAt: now
	}).returning();
	return created;
};
/**
* Get installation by GitHub installation ID
*/
const getInstallationByGitHubId = (db) => async (gitHubInstallationId) => {
	return await db.query.workAppGitHubInstallations.findFirst({ where: eq(workAppGitHubInstallations.installationId, gitHubInstallationId) }) ?? null;
};
/**
* Get installation by internal ID with tenant validation
*/
const getInstallationById = (db) => async (params) => {
	return await db.query.workAppGitHubInstallations.findFirst({ where: and(tenantScopedWhere(workAppGitHubInstallations, { tenantId: params.tenantId }), eq(workAppGitHubInstallations.id, params.id)) }) ?? null;
};
/**
* Get all installations for a tenant
*/
const getInstallationsByTenantId = (db) => async (params) => {
	const conditions = [tenantScopedWhere(workAppGitHubInstallations, { tenantId: params.tenantId })];
	if (!params.includeDisconnected) conditions.push(ne(workAppGitHubInstallations.status, "disconnected"));
	return await db.select().from(workAppGitHubInstallations).where(and(...conditions)).orderBy(desc(workAppGitHubInstallations.createdAt));
};
/**
* Update installation status
*/
const updateInstallationStatus = (db) => async (params) => {
	const now = (/* @__PURE__ */ new Date()).toISOString();
	const [updated] = await db.update(workAppGitHubInstallations).set({
		status: params.status,
		updatedAt: now
	}).where(and(tenantScopedWhere(workAppGitHubInstallations, { tenantId: params.tenantId }), eq(workAppGitHubInstallations.id, params.id))).returning();
	return updated ?? null;
};
/**
* Update installation status by GitHub installation ID (for webhook handlers)
*/
const updateInstallationStatusByGitHubId = (db) => async (params) => {
	const now = (/* @__PURE__ */ new Date()).toISOString();
	const [updated] = await db.update(workAppGitHubInstallations).set({
		status: params.status,
		updatedAt: now
	}).where(eq(workAppGitHubInstallations.installationId, params.gitHubInstallationId)).returning();
	return updated ?? null;
};
/**
* Soft delete an installation (set status to 'disconnected')
* Also removes all project repository access for this installation's repositories
*/
const disconnectInstallation = (db) => async (params) => {
	const now = (/* @__PURE__ */ new Date()).toISOString();
	const repoIds = (await db.select({ id: workAppGitHubRepositories.id }).from(workAppGitHubRepositories).where(eq(workAppGitHubRepositories.installationDbId, params.id))).map((r) => r.id);
	if (repoIds.length > 0) await db.delete(workAppGitHubProjectRepositoryAccess).where(inArray(workAppGitHubProjectRepositoryAccess.repositoryDbId, repoIds));
	const [updated] = await db.update(workAppGitHubInstallations).set({
		status: "disconnected",
		updatedAt: now
	}).where(and(tenantScopedWhere(workAppGitHubInstallations, { tenantId: params.tenantId }), eq(workAppGitHubInstallations.id, params.id))).returning();
	return !!updated;
};
/**
* Delete an installation (hard delete)
* Returns the deleted installation if found, null otherwise
*/
const deleteInstallation = (db) => async (params) => {
	const [deleted] = await db.delete(workAppGitHubInstallations).where(and(tenantScopedWhere(workAppGitHubInstallations, { tenantId: params.tenantId }), eq(workAppGitHubInstallations.id, params.id))).returning();
	return deleted ?? null;
};
/**
* Sync repositories for an installation
* Adds new repos, removes missing repos, updates existing
*/
const syncRepositories = (db) => async (params) => {
	const now = (/* @__PURE__ */ new Date()).toISOString();
	const existingRepos = await db.select().from(workAppGitHubRepositories).where(eq(workAppGitHubRepositories.installationDbId, params.installationId));
	const existingRepoIds = new Set(existingRepos.map((r) => r.repositoryId));
	const newRepoIds = new Set(params.repositories.map((r) => r.repositoryId));
	const toAdd = params.repositories.filter((r) => !existingRepoIds.has(r.repositoryId));
	const toRemove = existingRepos.filter((r) => !newRepoIds.has(r.repositoryId));
	const toUpdate = params.repositories.filter((r) => existingRepoIds.has(r.repositoryId));
	if (toRemove.length > 0) {
		const removeIds = toRemove.map((r) => r.id);
		await db.delete(workAppGitHubProjectRepositoryAccess).where(inArray(workAppGitHubProjectRepositoryAccess.repositoryDbId, removeIds));
		await db.delete(workAppGitHubRepositories).where(inArray(workAppGitHubRepositories.id, removeIds));
	}
	if (toAdd.length > 0) await db.insert(workAppGitHubRepositories).values(toAdd.map((repo) => ({
		id: generateId(),
		installationDbId: params.installationId,
		repositoryId: repo.repositoryId,
		repositoryName: repo.repositoryName,
		repositoryFullName: repo.repositoryFullName,
		private: repo.private,
		createdAt: now,
		updatedAt: now
	})));
	let updatedCount = 0;
	for (const repo of toUpdate) {
		const existing = existingRepos.find((e) => e.repositoryId === repo.repositoryId);
		if (existing && (existing.repositoryName !== repo.repositoryName || existing.repositoryFullName !== repo.repositoryFullName || existing.private !== repo.private)) {
			await db.update(workAppGitHubRepositories).set({
				repositoryName: repo.repositoryName,
				repositoryFullName: repo.repositoryFullName,
				private: repo.private,
				updatedAt: now
			}).where(eq(workAppGitHubRepositories.id, existing.id));
			updatedCount++;
		}
	}
	return {
		added: toAdd.length,
		removed: toRemove.length,
		updated: updatedCount
	};
};
/**
* Add repositories to an installation (for webhook 'added' events)
*/
const addRepositories = (db) => async (params) => {
	const now = (/* @__PURE__ */ new Date()).toISOString();
	if (params.repositories.length === 0) return [];
	await db.insert(workAppGitHubRepositories).values(params.repositories.map((repo) => ({
		id: generateId(),
		installationDbId: params.installationId,
		repositoryId: repo.repositoryId,
		repositoryName: repo.repositoryName,
		repositoryFullName: repo.repositoryFullName,
		private: repo.private,
		createdAt: now,
		updatedAt: now
	}))).onConflictDoNothing().returning();
	const insertedRepoIds = params.repositories.map((r) => r.repositoryId);
	return await db.select().from(workAppGitHubRepositories).where(and(eq(workAppGitHubRepositories.installationDbId, params.installationId), inArray(workAppGitHubRepositories.repositoryId, insertedRepoIds)));
};
/**
* Remove repositories from an installation (for webhook 'removed' events)
* Also removes associated project repository access entries
*/
const removeRepositories = (db) => async (params) => {
	if (params.repositoryIds.length === 0) return 0;
	const repoIds = (await db.select({ id: workAppGitHubRepositories.id }).from(workAppGitHubRepositories).where(and(eq(workAppGitHubRepositories.installationDbId, params.installationId), inArray(workAppGitHubRepositories.repositoryId, params.repositoryIds)))).map((r) => r.id);
	if (repoIds.length === 0) return 0;
	await db.delete(workAppGitHubProjectRepositoryAccess).where(inArray(workAppGitHubProjectRepositoryAccess.repositoryDbId, repoIds));
	return (await db.delete(workAppGitHubRepositories).where(inArray(workAppGitHubRepositories.id, repoIds)).returning()).length;
};
/**
* Get all repositories for an installation
*/
const getRepositoriesByInstallationId = (db) => async (installationId) => {
	return await db.select().from(workAppGitHubRepositories).where(eq(workAppGitHubRepositories.installationDbId, installationId)).orderBy(workAppGitHubRepositories.repositoryFullName);
};
/**
* Get repository by full name (e.g., "org/repo")
*/
const getRepositoryByFullName = (db) => async (repositoryFullName) => {
	return (await db.select().from(workAppGitHubRepositories).where(eq(workAppGitHubRepositories.repositoryFullName, repositoryFullName)).limit(1))[0] ?? null;
};
/**
* Get repository by internal ID
*/
const getRepositoryById = (db) => async (id) => {
	return await db.query.workAppGitHubRepositories.findFirst({ where: eq(workAppGitHubRepositories.id, id) }) ?? null;
};
/**
* Get all repositories for a tenant (across all installations)
*/
const getRepositoriesByTenantId = (db) => async (tenantId) => {
	return await db.select({
		id: workAppGitHubRepositories.id,
		installationDbId: workAppGitHubRepositories.installationDbId,
		installationId: workAppGitHubInstallations.installationId,
		repositoryId: workAppGitHubRepositories.repositoryId,
		repositoryName: workAppGitHubRepositories.repositoryName,
		repositoryFullName: workAppGitHubRepositories.repositoryFullName,
		private: workAppGitHubRepositories.private,
		createdAt: workAppGitHubRepositories.createdAt,
		updatedAt: workAppGitHubRepositories.updatedAt,
		installationAccountLogin: workAppGitHubInstallations.accountLogin
	}).from(workAppGitHubRepositories).innerJoin(workAppGitHubInstallations, eq(workAppGitHubRepositories.installationDbId, workAppGitHubInstallations.id)).where(and(tenantScopedWhere(workAppGitHubInstallations, { tenantId }), ne(workAppGitHubInstallations.status, "disconnected"))).orderBy(workAppGitHubRepositories.repositoryFullName);
};
/**
* Set project repository access (full replacement)
* Used when mode='selected' to specify which repositories the project can access.
* Pass empty array to clear all access entries.
*
* Also cascades changes to MCP tools: any MCP tool in this project with mode='selected'
* will have its selected repositories filtered to only include repos that remain
* in the project's access list.
*/
const setProjectRepositoryAccess = (db) => async (params) => {
	const now = (/* @__PURE__ */ new Date()).toISOString();
	const newRepoIdSet = new Set(params.repositoryIds);
	await db.delete(workAppGitHubProjectRepositoryAccess).where(eq(workAppGitHubProjectRepositoryAccess.projectId, params.projectId));
	if (params.repositoryIds.length > 0) await db.insert(workAppGitHubProjectRepositoryAccess).values(params.repositoryIds.map((repoId) => ({
		id: generateId(),
		tenantId: params.tenantId,
		projectId: params.projectId,
		repositoryDbId: repoId,
		createdAt: now,
		updatedAt: now
	})));
	const toolsWithSelectedMode = await db.select({ toolId: workAppGitHubMcpToolAccessMode.toolId }).from(workAppGitHubMcpToolAccessMode).where(and(projectScopedWhere(workAppGitHubMcpToolAccessMode, {
		tenantId: params.tenantId,
		projectId: params.projectId
	}), eq(workAppGitHubMcpToolAccessMode.mode, "selected")));
	for (const { toolId } of toolsWithSelectedMode) {
		const reposToRemove = (await db.select({
			id: workAppGitHubMcpToolRepositoryAccess.id,
			repositoryDbId: workAppGitHubMcpToolRepositoryAccess.repositoryDbId
		}).from(workAppGitHubMcpToolRepositoryAccess).where(eq(workAppGitHubMcpToolRepositoryAccess.toolId, toolId))).filter((r) => !newRepoIdSet.has(r.repositoryDbId));
		if (reposToRemove.length > 0) await db.delete(workAppGitHubMcpToolRepositoryAccess).where(inArray(workAppGitHubMcpToolRepositoryAccess.id, reposToRemove.map((r) => r.id)));
	}
};
/**
* Get project repository access entries
* These entries are used when mode='selected'. Check mode via getProjectAccessMode().
*/
const getProjectRepositoryAccess = (db) => async (projectId) => {
	return await db.select().from(workAppGitHubProjectRepositoryAccess).where(eq(workAppGitHubProjectRepositoryAccess.projectId, projectId));
};
/**
* Get project repository access with full repository details.
* If project access mode is 'all', returns all tenant repositories.
* If mode is 'selected' (or not set), returns only explicitly granted repositories.
*/
const getProjectRepositoryAccessWithDetails = (db) => async (params) => {
	if (await getProjectAccessMode(db)({
		tenantId: params.tenantId,
		projectId: params.projectId
	}) === "all") return (await getRepositoriesByTenantId(db)(params.tenantId)).map((repo) => ({
		accessId: repo.id,
		...repo
	}));
	return await db.select({
		accessId: workAppGitHubProjectRepositoryAccess.id,
		id: workAppGitHubRepositories.id,
		installationDbId: workAppGitHubRepositories.installationDbId,
		installationId: workAppGitHubInstallations.installationId,
		repositoryId: workAppGitHubRepositories.repositoryId,
		repositoryName: workAppGitHubRepositories.repositoryName,
		repositoryFullName: workAppGitHubRepositories.repositoryFullName,
		private: workAppGitHubRepositories.private,
		createdAt: workAppGitHubRepositories.createdAt,
		updatedAt: workAppGitHubRepositories.updatedAt,
		installationAccountLogin: workAppGitHubInstallations.accountLogin
	}).from(workAppGitHubProjectRepositoryAccess).innerJoin(workAppGitHubRepositories, eq(workAppGitHubProjectRepositoryAccess.repositoryDbId, workAppGitHubRepositories.id)).innerJoin(workAppGitHubInstallations, eq(workAppGitHubRepositories.installationDbId, workAppGitHubInstallations.id)).where(eq(workAppGitHubProjectRepositoryAccess.projectId, params.projectId));
};
/**
* Check if a project has access to a specific repository
* Returns true if:
* - Project mode is 'all' and repository belongs to tenant installations
* - Project mode is 'selected' and repository is explicitly in the project's access list
*/
const checkProjectRepositoryAccess = (db) => async (params) => {
	if (((await db.select({ mode: workAppGitHubProjectAccessMode.mode }).from(workAppGitHubProjectAccessMode).where(projectScopedWhere(workAppGitHubProjectAccessMode, {
		tenantId: params.tenantId,
		projectId: params.projectId
	})).limit(1))[0]?.mode ?? "selected") === "all") {
		if ((await db.select({ id: workAppGitHubRepositories.id }).from(workAppGitHubRepositories).innerJoin(workAppGitHubInstallations, eq(workAppGitHubRepositories.installationDbId, workAppGitHubInstallations.id)).where(and(eq(workAppGitHubRepositories.repositoryFullName, params.repositoryFullName), tenantScopedWhere(workAppGitHubInstallations, { tenantId: params.tenantId }), ne(workAppGitHubInstallations.status, "disconnected"))).limit(1)).length === 0) return {
			hasAccess: false,
			reason: "Repository not found in tenant installations"
		};
		return {
			hasAccess: true,
			reason: "Project has access to all repositories"
		};
	}
	if ((await db.select({ id: workAppGitHubProjectRepositoryAccess.id }).from(workAppGitHubProjectRepositoryAccess).innerJoin(workAppGitHubRepositories, eq(workAppGitHubProjectRepositoryAccess.repositoryDbId, workAppGitHubRepositories.id)).innerJoin(workAppGitHubInstallations, eq(workAppGitHubRepositories.installationDbId, workAppGitHubInstallations.id)).where(and(eq(workAppGitHubProjectRepositoryAccess.projectId, params.projectId), eq(workAppGitHubRepositories.repositoryFullName, params.repositoryFullName), tenantScopedWhere(workAppGitHubInstallations, { tenantId: params.tenantId }), ne(workAppGitHubInstallations.status, "disconnected"))).limit(1)).length === 0) return {
		hasAccess: false,
		reason: "Repository not in project access list"
	};
	return {
		hasAccess: true,
		reason: "Repository explicitly allowed for project"
	};
};
/**
* Remove all project repository access for a specific project
*/
const clearProjectRepositoryAccess = (db) => async (projectId) => {
	return (await db.delete(workAppGitHubProjectRepositoryAccess).where(eq(workAppGitHubProjectRepositoryAccess.projectId, projectId)).returning()).length;
};
/**
* Validate that all repository IDs belong to installations owned by a tenant
* Returns list of invalid repository IDs
*/
const validateRepositoryOwnership = (db) => async (params) => {
	if (params.repositoryIds.length === 0) return [];
	const validRepos = await db.select({ id: workAppGitHubRepositories.id }).from(workAppGitHubRepositories).innerJoin(workAppGitHubInstallations, eq(workAppGitHubRepositories.installationDbId, workAppGitHubInstallations.id)).where(and(tenantScopedWhere(workAppGitHubInstallations, { tenantId: params.tenantId }), ne(workAppGitHubInstallations.status, "disconnected"), inArray(workAppGitHubRepositories.id, params.repositoryIds)));
	const validRepoIds = new Set(validRepos.map((r) => r.id));
	return params.repositoryIds.filter((id) => !validRepoIds.has(id));
};
/**
* Get repository count for an installation
*/
const getRepositoryCount = (db) => async (installationId) => {
	const total = (await db.select({ count: count() }).from(workAppGitHubRepositories).where(eq(workAppGitHubRepositories.installationDbId, installationId)))[0]?.count ?? 0;
	return typeof total === "string" ? Number.parseInt(total, 10) : total;
};
/**
* Get repository counts for all installations belonging to a tenant
*/
const getRepositoryCountsByTenantId = (db) => async (params) => {
	const conditions = [tenantScopedWhere(workAppGitHubInstallations, { tenantId: params.tenantId })];
	if (!params.includeDisconnected) conditions.push(ne(workAppGitHubInstallations.status, "disconnected"));
	const results = await db.select({
		installationId: workAppGitHubInstallations.id,
		count: count(workAppGitHubRepositories.id)
	}).from(workAppGitHubInstallations).leftJoin(workAppGitHubRepositories, eq(workAppGitHubRepositories.installationDbId, workAppGitHubInstallations.id)).where(and(...conditions)).groupBy(workAppGitHubInstallations.id);
	const countsMap = /* @__PURE__ */ new Map();
	for (const row of results) {
		const total = typeof row.count === "string" ? Number.parseInt(row.count, 10) : row.count;
		countsMap.set(row.installationId, total);
	}
	return countsMap;
};
/**
* Set MCP tool repository access (full replacement)
* Used when mode='selected' to specify which repositories the tool can access.
* Pass empty array to clear all access entries.
*/
const setMcpToolRepositoryAccess = (db) => async (params) => {
	const now = (/* @__PURE__ */ new Date()).toISOString();
	await db.delete(workAppGitHubMcpToolRepositoryAccess).where(toolScopedWhere(workAppGitHubMcpToolRepositoryAccess, {
		tenantId: params.tenantId,
		projectId: params.projectId,
		toolId: params.toolId
	}));
	if (params.repositoryIds.length > 0) await db.insert(workAppGitHubMcpToolRepositoryAccess).values(params.repositoryIds.map((repoId) => ({
		id: generateId(),
		toolId: params.toolId,
		tenantId: params.tenantId,
		projectId: params.projectId,
		repositoryDbId: repoId,
		createdAt: now,
		updatedAt: now
	})));
};
/**
* Get MCP tool repository access entries
* These entries are used when mode='selected'. Check mode via getMcpToolAccessMode().
*/
const getMcpToolRepositoryAccess = (db) => async (scope) => {
	return await db.select().from(workAppGitHubMcpToolRepositoryAccess).where(toolScopedWhere(workAppGitHubMcpToolRepositoryAccess, scope));
};
/**
* Get MCP tool repository access with full repository details.
* If the tool's access mode is 'all', returns all repositories the project has access to.
* If mode is 'selected' (or not set), returns only explicitly granted repositories.
*/
const getMcpToolRepositoryAccessWithDetails = (db) => async (scope) => {
	if ((await db.select({
		mode: workAppGitHubMcpToolAccessMode.mode,
		projectId: workAppGitHubMcpToolAccessMode.projectId,
		tenantId: workAppGitHubMcpToolAccessMode.tenantId
	}).from(workAppGitHubMcpToolAccessMode).where(toolScopedWhere(workAppGitHubMcpToolAccessMode, scope)).limit(1))[0]?.mode === "all") return getProjectRepositoryAccessWithDetails(db)({
		tenantId: scope.tenantId,
		projectId: scope.projectId
	});
	return await db.select({
		accessId: workAppGitHubMcpToolRepositoryAccess.id,
		id: workAppGitHubRepositories.id,
		installationDbId: workAppGitHubRepositories.installationDbId,
		installationId: workAppGitHubInstallations.installationId,
		repositoryId: workAppGitHubRepositories.repositoryId,
		repositoryName: workAppGitHubRepositories.repositoryName,
		repositoryFullName: workAppGitHubRepositories.repositoryFullName,
		private: workAppGitHubRepositories.private,
		createdAt: workAppGitHubRepositories.createdAt,
		updatedAt: workAppGitHubRepositories.updatedAt,
		installationAccountLogin: workAppGitHubInstallations.accountLogin
	}).from(workAppGitHubMcpToolRepositoryAccess).innerJoin(workAppGitHubRepositories, eq(workAppGitHubMcpToolRepositoryAccess.repositoryDbId, workAppGitHubRepositories.id)).innerJoin(workAppGitHubInstallations, eq(workAppGitHubRepositories.installationDbId, workAppGitHubInstallations.id)).where(toolScopedWhere(workAppGitHubMcpToolRepositoryAccess, scope));
};
/**
* Remove all MCP tool repository access for a specific tool
*/
const clearMcpToolRepositoryAccess = (db) => async (scope) => {
	return (await db.delete(workAppGitHubMcpToolRepositoryAccess).where(toolScopedWhere(workAppGitHubMcpToolRepositoryAccess, scope)).returning()).length;
};
const isGithubWorkAppTool = (tool) => {
	return tool.isWorkApp && tool.config.mcp.server.url.includes("/github/mcp");
};
/**
* Set the access mode for a project's GitHub repository access.
* - 'all': Project has access to all repositories from tenant GitHub installations
* - 'selected': Project only has access to repositories listed in work_app_github_project_repository_access
*/
const setProjectAccessMode = (db) => async (params) => {
	const now = (/* @__PURE__ */ new Date()).toISOString();
	await db.insert(workAppGitHubProjectAccessMode).values({
		tenantId: params.tenantId,
		projectId: params.projectId,
		mode: params.mode,
		createdAt: now,
		updatedAt: now
	}).onConflictDoUpdate({
		target: [workAppGitHubProjectAccessMode.tenantId, workAppGitHubProjectAccessMode.projectId],
		set: {
			mode: params.mode,
			updatedAt: now
		}
	});
};
/**
* Get the access mode for a project's GitHub repository access.
* Returns 'selected' if no mode is explicitly set (fail-safe default).
*/
const getProjectAccessMode = (db) => async (params) => {
	return (await db.select({ mode: workAppGitHubProjectAccessMode.mode }).from(workAppGitHubProjectAccessMode).where(projectScopedWhere(workAppGitHubProjectAccessMode, params)).limit(1))[0]?.mode ?? "selected";
};
/**
* Delete the access mode entry for a project
*/
const deleteProjectAccessMode = (db) => async (params) => {
	return (await db.delete(workAppGitHubProjectAccessMode).where(projectScopedWhere(workAppGitHubProjectAccessMode, params)).returning()).length > 0;
};
/**
* Set the access mode for an MCP tool's GitHub repository access.
* - 'all': Tool has access to all repositories the project has access to
* - 'selected': Tool only has access to repositories listed in work_app_github_mcp_tool_repository_access
*/
const setMcpToolAccessMode = (db) => async (params) => {
	const now = (/* @__PURE__ */ new Date()).toISOString();
	await db.insert(workAppGitHubMcpToolAccessMode).values({
		toolId: params.toolId,
		tenantId: params.tenantId,
		projectId: params.projectId,
		mode: params.mode,
		createdAt: now,
		updatedAt: now
	}).onConflictDoUpdate({
		target: [
			workAppGitHubMcpToolAccessMode.tenantId,
			workAppGitHubMcpToolAccessMode.projectId,
			workAppGitHubMcpToolAccessMode.toolId
		],
		set: {
			mode: params.mode,
			updatedAt: now
		}
	});
};
/**
* Get the access mode for an MCP tool's GitHub repository access.
* Returns 'selected' if no mode is explicitly set (fail-safe default).
*/
const getMcpToolAccessMode = (db) => async (scope) => {
	return (await db.select({ mode: workAppGitHubMcpToolAccessMode.mode }).from(workAppGitHubMcpToolAccessMode).where(toolScopedWhere(workAppGitHubMcpToolAccessMode, scope)).limit(1))[0]?.mode ?? "selected";
};
/**
* Delete the access mode entry for an MCP tool
*/
const deleteMcpToolAccessMode = (db) => async (scope) => {
	return (await db.delete(workAppGitHubMcpToolAccessMode).where(toolScopedWhere(workAppGitHubMcpToolAccessMode, scope)).returning()).length > 0;
};

//#endregion
export { addRepositories, checkProjectRepositoryAccess, clearMcpToolRepositoryAccess, clearProjectRepositoryAccess, createInstallation, deleteInstallation, deleteMcpToolAccessMode, deleteProjectAccessMode, disconnectInstallation, getInstallationByGitHubId, getInstallationById, getInstallationsByTenantId, getMcpToolAccessMode, getMcpToolRepositoryAccess, getMcpToolRepositoryAccessWithDetails, getProjectAccessMode, getProjectRepositoryAccess, getProjectRepositoryAccessWithDetails, getRepositoriesByInstallationId, getRepositoriesByTenantId, getRepositoryByFullName, getRepositoryById, getRepositoryCount, getRepositoryCountsByTenantId, isGithubWorkAppTool, removeRepositories, setMcpToolAccessMode, setMcpToolRepositoryAccess, setProjectAccessMode, setProjectRepositoryAccess, syncRepositories, updateInstallationStatus, updateInstallationStatusByGitHubId, validateRepositoryOwnership };