import { createSchemaCacheTable, schemaKeyToCacheTableName, } from "./create-schema-cache-table.js";
import { LixVersionDescriptorSchema } from "../../version/schema-definition.js";
// Cache of physical tables scoped to each Lix instance
// Using WeakMap ensures proper cleanup when Lix instances are garbage collected
const stateCacheTablesMap = new WeakMap();
export function getStateCacheTables(args) {
    let cache = stateCacheTablesMap.get(args.engine.runtimeCacheRef);
    if (!cache) {
        cache = new Set();
        stateCacheTablesMap.set(args.engine.runtimeCacheRef, cache);
    }
    return cache;
}
export function applyStateCacheSchema(args) {
    const { sqlite } = args.engine;
    // Get or create cache for this Lix instance
    const tableCache = getStateCacheTables({ engine: args.engine });
    // Initialize cache with existing tables on startup
    const existingTables = sqlite.exec({
        sql: `SELECT name FROM sqlite_schema WHERE type='table' AND name LIKE 'lix_internal_state_cache_v1_%'`,
        returnValue: "resultRows",
    });
    if (existingTables) {
        for (const row of existingTables) {
            tableCache.add(row[0]);
        }
    }
    // Ensure descriptor cache table exists for inheritance rewrites
    const descriptorTable = schemaKeyToCacheTableName("lix_version_descriptor");
    if (!tableCache.has(descriptorTable)) {
        const created = createSchemaCacheTable({
            engine: args.engine,
            schema: LixVersionDescriptorSchema,
        });
        tableCache.add(created);
        if (created !== descriptorTable) {
            tableCache.add(descriptorTable);
        }
    }
}
//# sourceMappingURL=schema.js.map