/**
 * session-fts-repair.test.mjs — regression tests for session FTS schema repair.
 *
 * Purpose: prove sf-db can reopen a DB that contains orphaned FTS5 shadow
 * tables from an interrupted or partial `turns_fts` migration.
 */
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { afterEach, test } from "vitest";
import { closeDatabase, openDatabase } from "../sf-db.js";

const tmpRoots = [];

afterEach(() => {
	closeDatabase();
	for (const root of tmpRoots.splice(0)) {
		rmSync(root, { recursive: true, force: true });
	}
});

function makeDbPath() {
	const root = mkdtempSync(join(tmpdir(), "sf-session-fts-repair-"));
	mkdirSync(join(root, ".sf"), { recursive: true });
	tmpRoots.push(root);
	return join(root, ".sf", "sf.db");
}

test("openDatabase_when_turns_fts_shadow_tables_are_orphaned_repairs_schema", () => {
	const dbPath = makeDbPath();
	const raw = new DatabaseSync(dbPath);
	raw.exec(`
    CREATE TABLE turns_fts_data(id INTEGER PRIMARY KEY, block BLOB);
    CREATE TABLE turns_fts_idx(segid INTEGER, term TEXT, pgno INTEGER);
    CREATE TABLE turns_fts_docsize(id INTEGER PRIMARY KEY, sz BLOB);
    CREATE TABLE turns_fts_config(k PRIMARY KEY, v) WITHOUT ROWID;
  `);
	raw.close();

	assert.equal(openDatabase(dbPath), true);
	closeDatabase();

	const repaired = new DatabaseSync(dbPath);
	const table = repaired
		.prepare(
			"SELECT name FROM sqlite_master WHERE type='table' AND name='turns_fts'",
		)
		.get();
	assert.equal(table.name, "turns_fts");
	repaired.close();
});
