import "server-only";

import { mkdirSync } from "node:fs";
import { dirname, resolve } from "node:path";
import Database from "better-sqlite3";
import { getAddress } from "viem";

let database: Database.Database | null = null;

const getDatabase = () => {
  if (database) return database;
  const databasePath = resolve(process.env.AGENT_EVENT_DB_PATH ?? "data/agent-events.db");
  mkdirSync(dirname(databasePath), { recursive: true });
  database = new Database(databasePath);
  database.pragma("journal_mode = WAL");
  database.exec(`
    CREATE TABLE IF NOT EXISTS operator_wallets (
      address TEXT PRIMARY KEY,
      created_at TEXT NOT NULL,
      updated_at TEXT NOT NULL
    );
  `);
  return database;
};

export const registerOperatorWallet = (address: string) => {
  const normalized = getAddress(address).toLowerCase();
  const now = new Date().toISOString();
  getDatabase().prepare(`
    INSERT INTO operator_wallets(address, created_at, updated_at)
    VALUES(?, ?, ?)
    ON CONFLICT(address) DO UPDATE SET updated_at = excluded.updated_at
  `).run(normalized, now, now);
  return normalized;
};

export const listOperatorWallets = () => {
  const rows = getDatabase()
    .prepare("SELECT address FROM operator_wallets ORDER BY created_at ASC")
    .all() as Array<{ address: string }>;
  return rows.map((row) => getAddress(row.address).toLowerCase());
};
