import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
import * as schema from './schema';
import { existsSync, mkdirSync } from 'fs';
import { dirname, join } from 'path';

const DATA_DIR = process.env.DATA_DIR || './data';
const DB_PATH = join(DATA_DIR, 'taskplaner.db');

// Ensure data directory exists
const dbDir = dirname(DB_PATH);
if (!existsSync(dbDir)) {
	mkdirSync(dbDir, { recursive: true });
}

const sqlite = new Database(DB_PATH);

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

// Initialize schema if tables don't exist
const tableExists = sqlite
	.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='entries'")
	.get();

if (!tableExists) {
	sqlite.exec(`
		CREATE TABLE entries (
			id TEXT PRIMARY KEY,
			title TEXT,
			content TEXT NOT NULL,
			type TEXT NOT NULL DEFAULT 'thought' CHECK(type IN ('task', 'thought')),
			status TEXT DEFAULT 'open' CHECK(status IN ('open', 'done', 'archived')),
			pinned INTEGER DEFAULT 0,
			due_date TEXT,
			created_at TEXT NOT NULL,
			updated_at TEXT NOT NULL
		);

		CREATE TABLE images (
			id TEXT PRIMARY KEY,
			entry_id TEXT NOT NULL REFERENCES entries(id) ON DELETE CASCADE,
			filename TEXT NOT NULL,
			ext TEXT NOT NULL,
			created_at TEXT NOT NULL
		);

		CREATE TABLE tags (
			id TEXT PRIMARY KEY,
			name TEXT NOT NULL,
			created_at TEXT NOT NULL
		);
		CREATE UNIQUE INDEX tagNameUniqueIndex ON tags(lower(name));

		CREATE TABLE entry_tags (
			entry_id TEXT NOT NULL REFERENCES entries(id) ON DELETE CASCADE,
			tag_id TEXT NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
			PRIMARY KEY (entry_id, tag_id)
		);
	`);
	console.log('Database schema initialized');
}

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

export { schema };
