import { test, expect } from "vitest";
import { openLix } from "../../lix/open-lix.js";
import { createSchemaCacheTable, schemaKeyToCacheTableName, } from "./create-schema-cache-table.js";
const TEST_CACHE_SCHEMA = {
    "x-lix-key": "lix_test_create",
    "x-lix-version": "1.0",
    type: "object",
    additionalProperties: false,
    properties: {},
};
test("createSchemaCacheTable creates table with core indexes and is idempotent", async () => {
    const lix = await openLix({});
    const tableName = schemaKeyToCacheTableName(TEST_CACHE_SCHEMA["x-lix-key"]);
    // First call should create the table and indexes
    createSchemaCacheTable({ engine: lix.engine, schema: TEST_CACHE_SCHEMA });
    // Verify table exists and WITHOUT ROWID
    const tbl = lix.engine.sqlite.exec({
        sql: `SELECT name, sql FROM sqlite_schema WHERE type='table' AND name = ?`,
        bind: [tableName],
        returnValue: "resultRows",
        rowMode: "object",
    });
    expect(tbl?.[0]?.name).toBe(tableName);
    expect(String(tbl?.[0]?.sql || "")).toMatch(/WITHOUT ROWID/);
    // Verify core indexes exist
    const idxRows = lix.engine.sqlite.exec({
        sql: `SELECT name, sql FROM sqlite_schema WHERE type='index' AND tbl_name = ? ORDER BY name`,
        bind: [tableName],
        returnValue: "resultRows",
        rowMode: "object",
    });
    const names = new Set(idxRows.map((r) => r.name));
    expect(Array.from(names)).toEqual(expect.arrayContaining([
        `idx_${tableName}_version_id`,
        `idx_${tableName}_vfe`,
        `idx_${tableName}_fv`,
    ]));
    // Second call should be a no-op (idempotent)
    createSchemaCacheTable({ engine: lix.engine, schema: TEST_CACHE_SCHEMA });
    const idxRows2 = lix.engine.sqlite.exec({
        sql: `SELECT name FROM sqlite_schema WHERE type='index' AND tbl_name = ?`,
        bind: [tableName],
        returnValue: "resultRows",
    });
    // Still contains the same three core indexes (no duplicates)
    const idxCount = idxRows2.filter((r) => String(r?.[0] || "").startsWith(`idx_${tableName}_`)).length;
    expect(idxCount).toBeGreaterThanOrEqual(3);
});
//# sourceMappingURL=create-schema-cache-table.test.js.map