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

let db: BetterSqlite3.Database | null = null;
let insertStmt: BetterSqlite3.Statement | null = null;

function getDb() {
  if (db) return db;

  try {
    const SERVER_STORAGE = '/server_storage';
    let dbDir: string;
    try {
      fs.accessSync(SERVER_STORAGE, fs.constants.W_OK);
      dbDir = SERVER_STORAGE;
    } catch {
      dbDir = process.cwd();
    }

    const dbPath = path.join(dbDir, 'visitors.db');
    db = new Database(dbPath);
    db.pragma('journal_mode = WAL');

    db.exec(`
      CREATE TABLE IF NOT EXISTS visits (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        ip_address TEXT NOT NULL,
        path TEXT NOT NULL,
        visited_at TEXT NOT NULL DEFAULT (datetime('now'))
      );
    `);

    insertStmt = db.prepare(
      'INSERT INTO visits (ip_address, path) VALUES (?, ?)'
    );

    return db;
  } catch (e) {
    console.error('Failed to initialize SQLite database:', e);
    db = null;
    insertStmt = null;
    return null;
  }
}

export function logVisit(ip: string, visitPath: string) {
  const database = getDb();
  if (!database || !insertStmt) return;
  insertStmt.run(ip, visitPath);
}
