import Database from "better-sqlite3";
import path from "path";
import fs from "fs";
const DATA_DIR = path.join(import.meta.dirname, "..", "data");
fs.mkdirSync(DATA_DIR, { recursive: true });
const db = new Database(path.join(DATA_DIR, "shadowdark.db"));
db.pragma("journal_mode = WAL");
db.pragma("foreign_keys = ON");
db.exec(`
    CREATE TABLE IF NOT EXISTS campaigns (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        created_by TEXT DEFAULT '',
        created_at TEXT DEFAULT (datetime('now'))
    );

    CREATE TABLE IF NOT EXISTS characters (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        campaign_id INTEGER NOT NULL REFERENCES campaigns(id) ON DELETE CASCADE,
        created_by TEXT DEFAULT '',
        name TEXT NOT NULL,
        class TEXT NOT NULL DEFAULT 'Fighter',
        ancestry TEXT NOT NULL DEFAULT 'Human',
        level INTEGER NOT NULL DEFAULT 1,
        xp INTEGER NOT NULL DEFAULT 0,
        hp_current INTEGER NOT NULL DEFAULT 0,
        hp_max INTEGER NOT NULL DEFAULT 0,
        ac INTEGER NOT NULL DEFAULT 10,
        alignment TEXT NOT NULL DEFAULT 'Neutral',
        title TEXT DEFAULT '',
        notes TEXT DEFAULT ''
    );

    CREATE TABLE IF NOT EXISTS character_stats (
        character_id INTEGER NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
        stat_name TEXT NOT NULL,
        value INTEGER NOT NULL DEFAULT 10,
        PRIMARY KEY (character_id, stat_name)
    );

    CREATE TABLE IF NOT EXISTS character_gear (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        character_id INTEGER NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
        name TEXT NOT NULL,
        type TEXT NOT NULL DEFAULT 'gear',
        slot_count INTEGER NOT NULL DEFAULT 1,
        properties TEXT DEFAULT '{}'
    );

    CREATE TABLE IF NOT EXISTS character_talents (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        character_id INTEGER NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
        name TEXT NOT NULL,
        description TEXT DEFAULT '',
        effect TEXT DEFAULT '{}'
    );
`);
export default db;
