import Database from 'better-sqlite3';
import fs from 'fs';
import path from 'path';

const DB_PATH = path.join(process.cwd(), 'data', 'strike-arena.db');
const INIT_SQL = path.join(process.cwd(), 'init', 'init.sqlite.sql');

function openDb(): Database.Database {
    const dir = path.dirname(DB_PATH);
    if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });

    const db = new Database(DB_PATH);
    db.pragma('journal_mode = WAL');
    db.pragma('foreign_keys = ON');

    // Seed on first run (no tables yet)
    const tables = db.prepare("SELECT count(*) as n FROM sqlite_master WHERE type='table'").get() as { n: number };
    if (tables.n === 0 && fs.existsSync(INIT_SQL)) {
        const sql = fs.readFileSync(INIT_SQL, 'utf-8');
        db.exec(sql);
    }

    return db;
}

// Singleton: reuse across hot-reload in dev
declare global {
    // eslint-disable-next-line no-var
    var __sqlite_db: Database.Database | undefined;
}

const db: Database.Database = global.__sqlite_db ?? (global.__sqlite_db = openDb());

function isSelect(sql: string) {
    return /^\s*(SELECT|PRAGMA|WITH)/i.test(sql.trim());
}

export const bd = {
    query: async (sql: string, params: unknown[] = []): Promise<any[]> => {
        const stmt = db.prepare(sql);
        if (isSelect(sql)) {
            return [stmt.all(...(params as any[]))];
        }
        const info = stmt.run(...(params as any[]));
        return [{ insertId: info.lastInsertRowid, affectedRows: info.changes }];
    },
    execute: async (sql: string, params: unknown[] = []): Promise<any[]> => {
        return bd.query(sql, params);
    },
};
