import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { test, afterEach } from 'vitest';

import { handleInspect } from "../commands-inspect.ts";
import { closeDatabase, openDatabase } from "../sf-db.ts";

test("/sf inspect opens existing database when it was not yet opened in session", async (t) => {
	closeDatabase();

	const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "sf-inspect-db-"));
	const prevCwd = process.cwd();

	afterEach(() => {
		process.chdir(prevCwd);
		closeDatabase();
		fs.rmSync(tmp, { recursive: true, force: true });
	});

	const sfDir = path.join(tmp, ".sf");
	fs.mkdirSync(sfDir, { recursive: true });
	const dbPath = path.join(sfDir, "sf.db");

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

	process.chdir(tmp);

	const notifications: Array<{ message: string; level: string }> = [];
	const ctx = {
		ui: {
			notify(message: string, level: string) {
				notifications.push({ message, level });
			},
		},
	} as any;

	await handleInspect(ctx);

	assert.equal(notifications.length, 1);
	assert.equal(notifications[0].level, "info");
	assert.match(notifications[0].message, /=== SF Database Inspect ===/);
	assert.doesNotMatch(notifications[0].message, /No SF database available/);
});
