import Database from 'better-sqlite3';
import type { Database as DBType } from 'better-sqlite3';

export function initSchema(db: DBType): void {
  db.pragma('journal_mode = WAL');
  db.pragma('foreign_keys = ON');

  db.exec(`
    CREATE TABLE IF NOT EXISTS modules (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL UNIQUE,
      path TEXT NOT NULL,
      language TEXT NOT NULL DEFAULT 'ts',
      service TEXT,
      type TEXT NOT NULL DEFAULT 'module'
    );

    CREATE TABLE IF NOT EXISTS symbols (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      module_id INTEGER NOT NULL,
      name TEXT NOT NULL,
      kind TEXT NOT NULL,
      language TEXT NOT NULL,
      file_path TEXT NOT NULL,
      line_start INTEGER,
      line_end INTEGER,
      is_exported INTEGER DEFAULT 0,
      is_public INTEGER DEFAULT 0,
      FOREIGN KEY (module_id) REFERENCES modules(id)
    );

    CREATE TABLE IF NOT EXISTS calls (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      caller_id INTEGER,
      callee_id INTEGER,
      callee_name TEXT NOT NULL,
      file_path TEXT NOT NULL,
      line INTEGER,
      FOREIGN KEY (caller_id) REFERENCES symbols(id),
      FOREIGN KEY (callee_id) REFERENCES symbols(id)
    );

    CREATE TABLE IF NOT EXISTS dependencies (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      source_module_id INTEGER NOT NULL,
      target_module_id INTEGER NOT NULL,
      FOREIGN KEY (source_module_id) REFERENCES modules(id),
      FOREIGN KEY (target_module_id) REFERENCES modules(id),
      UNIQUE (source_module_id, target_module_id)
    );

    CREATE TABLE IF NOT EXISTS contracts (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL,
      type TEXT NOT NULL,
      file_path TEXT NOT NULL,
      service TEXT,
      content TEXT
    );

    CREATE TABLE IF NOT EXISTS events (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name TEXT NOT NULL,
      producer_module_id INTEGER,
      consumer_count INTEGER DEFAULT 0,
      file_path TEXT,
      FOREIGN KEY (producer_module_id) REFERENCES modules(id)
    );

    CREATE INDEX IF NOT EXISTS idx_symbols_module ON symbols(module_id);
    CREATE INDEX IF NOT EXISTS idx_symbols_name ON symbols(name);
    CREATE INDEX IF NOT EXISTS idx_calls_caller ON calls(caller_id);
    CREATE INDEX IF NOT EXISTS idx_calls_callee_name ON calls(callee_name);
    CREATE INDEX IF NOT EXISTS idx_deps_source ON dependencies(source_module_id);
    CREATE INDEX IF NOT EXISTS idx_deps_target ON dependencies(target_module_id);
  `);
}

export function createDb(dbPath: string = 'arch.db'): DBType {
  const db = new Database(dbPath);
  initSchema(db);
  return db;
}