import path from "node:path";
import { fileURLToPath } from "node:url";
import { DatabaseSync } from "node:sqlite";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const DEFAULT_DB_PATH = path.resolve(__dirname, "../data/geocoder.sqlite");

let _db = null;
let _path = null;

export function getDbPath() {
  return path.resolve(process.env.GEOCODER_DB_PATH || DEFAULT_DB_PATH);
}

export function getDb() {
  const filePath = getDbPath();
  if (_db && _path === filePath) return _db;
  if (_db) _db.close();
  _db = new DatabaseSync(filePath);
  _db.exec("PRAGMA journal_mode = WAL");
  _path = filePath;
  return _db;
}

export function ensureSchema(db = getDb()) {
  db.exec(`
    CREATE TABLE IF NOT EXISTS gazetteer_places (
      id            TEXT PRIMARY KEY,
      state_code    TEXT NOT NULL,
      name          TEXT NOT NULL,
      full_name     TEXT NOT NULL,
      city_key      TEXT NOT NULL,
      full_city_key TEXT NOT NULL,
      lsad          TEXT NOT NULL,
      lsad_priority INTEGER NOT NULL,
      geoid         TEXT NOT NULL,
      latitude      REAL NOT NULL,
      longitude     REAL NOT NULL
    );
    CREATE INDEX IF NOT EXISTS idx_state_city      ON gazetteer_places(state_code, city_key);
    CREATE INDEX IF NOT EXISTS idx_state_full_city ON gazetteer_places(state_code, full_city_key);
  `);
}

export function closeDb() {
  if (_db) {
    _db.close();
    _db = null;
    _path = null;
  }
}
