import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
import type { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';

import { getDbPath, ensureDbDirectory } from './config.js';
import * as schema from './schema.js';

export type DrizzleDatabase = BetterSQLite3Database<typeof schema>;

/**
 * Create a new database connection.
 *
 * This is a factory function (not a singleton) to allow multiple instances
 * for testing with isolated databases.
 *
 * @param path - Optional path override. Defaults to getDbPath().
 *               Use ':memory:' for in-memory testing database.
 * @returns Drizzle database instance with schema
 */
export function createDatabase(path?: string): DrizzleDatabase {
  const dbPath = path ?? getDbPath();

  // Ensure directory exists for file-based databases
  ensureDbDirectory(dbPath);

  // Create SQLite connection
  const sqlite = new Database(dbPath);

  // Enable WAL mode for better concurrent read performance
  sqlite.pragma('journal_mode = WAL');

  // Enable foreign keys (SQLite has them disabled by default)
  sqlite.pragma('foreign_keys = ON');

  // Create Drizzle instance with schema
  return drizzle(sqlite, { schema });
}

// Re-export config utilities
export { getDbPath, ensureDbDirectory } from './config.js';

// Re-export schema initialization
export { ensureSchema } from './ensure-schema.js';

// Re-export schema and types
export * from './schema.js';

// Re-export repository interfaces (ports)
export * from './repositories/index.js';

// Re-export Drizzle adapters
export * from './repositories/drizzle/index.js';
