import { drizzle } from 'drizzle-orm/better-sqlite3';
import { migrate } from 'drizzle-orm/better-sqlite3/migrator';
import Database from 'better-sqlite3';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { join, dirname } from 'node:path';
import * as schema from './schema';
import { env } from '$env/dynamic/private';

if (!env.DATABASE_URL) throw new Error('DATABASE_URL is not set');

const client = new Database(env.DATABASE_URL);

// Enable WAL mode for better concurrent read performance.
client.pragma('journal_mode = WAL');
// Enforce foreign key constraints.
client.pragma('foreign_keys = ON');

export const db = drizzle(client, { schema });

// ---------------------------------------------------------------------------
// Database initialisation — run on startup
// ---------------------------------------------------------------------------

const __dirname = dirname(fileURLToPath(import.meta.url));

/**
 * Run Drizzle migrations then apply the FTS5 virtual table and triggers.
 * Safe to call multiple times — all DDL uses IF NOT EXISTS guards.
 */
export function initializeDatabase(): void {
	const migrationsFolder = join(__dirname, 'migrations');
	migrate(db, { migrationsFolder });

	// Apply FTS5 virtual table and trigger DDL (not expressible via Drizzle).
	// exec() handles multi-statement SQL with embedded comments correctly.
	const ftsSql = readFileSync(join(__dirname, 'fts.sql'), 'utf-8');
	client.exec(ftsSql);
}
