// Test setup: opens an in-memory SQLite database, applies all migrations.
// Each vitest worker fork gets its own globalThis, so each test file gets a
// fresh DB. db.ts reads BIFROST_DB_PATH at import time, so this must run first.

process.env.BIFROST_DB_PATH = ':memory:';

import { readFileSync, readdirSync } from 'fs';
import { join } from 'path';
import type Database from 'better-sqlite3';

// Importing db.ts triggers the singleton against ':memory:'.
await import('../src/lib/db.js');

const db = (globalThis as typeof globalThis & { __bifrost_db?: Database.Database }).__bifrost_db;
if (!db) throw new Error('db singleton did not initialise against :memory:');

const migrationsDir = join(process.cwd(), 'migrations');
const files = readdirSync(migrationsDir).filter(f => f.endsWith('.sql')).sort();
for (const file of files) {
  db.exec(readFileSync(join(migrationsDir, file), 'utf8'));
}
