import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, it } from "vitest";

const srcPath = join(import.meta.dirname, "..", "auto-start.ts");
const src = readFileSync(srcPath, "utf-8");

describe("#2841: cold DB opened before initial deriveState", () => {
	it("defines openProjectDbIfPresent helper", () => {
		const helperIdx = src.indexOf("async function openProjectDbIfPresent");
		assert.ok(helperIdx >= 0);
	});

	it("pre-derive DB helper resolves the project-root DB path", () => {
		const helperIdx = src.indexOf("async function openProjectDbIfPresent");
		const helperRegion = helperIdx >= 0 ? src.slice(helperIdx, helperIdx + 500) : "";
		assert.ok(
			helperRegion.includes("resolveProjectRootDbPath(basePath)"),
		);
	});

	it("pre-derive DB helper opens the resolved DB path", () => {
		const helperIdx = src.indexOf("async function openProjectDbIfPresent");
		const helperRegion = helperIdx >= 0 ? src.slice(helperIdx, helperIdx + 500) : "";
		assert.ok(helperRegion.includes("openDatabase(sfDbPath)"));
	});

	it("auto-start.ts has the initial deriveState(base) call", () => {
		const firstDeriveIdx = src.indexOf("let state = await deriveState(base);");
		assert.ok(firstDeriveIdx > 0);
	});

	it("bootstrapAutoSession opens the DB before the first deriveState(base) call", () => {
		const firstDeriveIdx = src.indexOf("let state = await deriveState(base);");
		const preDeriveRegion = firstDeriveIdx > 0 ? src.slice(0, firstDeriveIdx) : "";
		const preDeriveOpenIdx = preDeriveRegion.lastIndexOf(
			"await openProjectDbIfPresent(base);",
		);
		assert.ok(
			preDeriveOpenIdx > 0,
			"bootstrapAutoSession opens the DB before the first deriveState(base) call",
		);
	});
});
