import { type Client, createClient } from "@libsql/client";
import { ENCRYPTION_KEY } from "./config";
import { browser } from "$app/environment";

const db = browser ? null : createClient({
  url: "file:/data/portal-btc.db",
  encryptionKey: ENCRYPTION_KEY,
});

let tablesCreated = false;

export async function getDb(): Promise<Client> {
  if (browser) throw new Error("getDb can only be called on the server");
  if (!db) throw new Error("Database not initialized");
  if (!tablesCreated) {
    await db.batch(
      [
        "CREATE TABLE IF NOT EXISTS users (username TEXT, npub TEXT)",
      ],
      "write",
    );
    tablesCreated = true;
  }
  return db;
}
