import { manage_schema_exports } from "../db/manage/manage-schema.js";
import { getTableConfig } from "drizzle-orm/pg-core";

//#region src/dolt/fk-map.ts
function buildFkDepsFromSchema() {
	const deps = {};
	for (const value of Object.values(manage_schema_exports)) {
		if (value == null || typeof value !== "object") continue;
		let config;
		try {
			config = getTableConfig(value);
		} catch {
			continue;
		}
		if (!config?.name) continue;
		const tableDeps = /* @__PURE__ */ new Set();
		for (const fk of config.foreignKeys ?? []) {
			const ref = fk.reference();
			let refName;
			try {
				refName = getTableConfig(ref.foreignTable).name;
			} catch {
				continue;
			}
			if (refName && refName !== config.name) tableDeps.add(refName);
		}
		if (tableDeps.size > 0) deps[config.name] = [...tableDeps];
	}
	return deps;
}
const manageFkDeps = buildFkDepsFromSchema();
function buildFkColumnLinksFromSchema() {
	const links = [];
	for (const value of Object.values(manage_schema_exports)) {
		if (value == null || typeof value !== "object") continue;
		let config;
		try {
			config = getTableConfig(value);
		} catch {
			continue;
		}
		if (!config?.name) continue;
		for (const fk of config.foreignKeys ?? []) {
			const ref = fk.reference();
			let parentName;
			try {
				parentName = getTableConfig(ref.foreignTable).name;
			} catch {
				continue;
			}
			if (!parentName || parentName === config.name) continue;
			const childCols = ref.columns.map((c) => c.name);
			const parentCols = ref.foreignColumns.map((c) => c.name);
			if (childCols.length !== parentCols.length || childCols.length === 0) continue;
			links.push({
				childTable: config.name,
				parentTable: parentName,
				columns: childCols.map((child, i) => ({
					child,
					parent: parentCols[i]
				}))
			});
		}
	}
	return links;
}
const manageFkColumnLinks = buildFkColumnLinksFromSchema();

//#endregion
export { manageFkColumnLinks, manageFkDeps };