import { join } from 'node:path';
import { PGlite } from '@electric-sql/pglite';
import { CamelCasePlugin, Kysely } from 'kysely';
import { KyselyPGlite } from 'kysely-pglite';
import type { DB } from '../v1.generated';

export const root = join(__dirname, '../..');
export const dumpPath = join(root, '.data.tar');

export async function useLocalKysely() {
  let isDestroyed = false;
  const now = performance.now();

  const dump = Bun.file(dumpPath);

  const pglite = new PGlite({ loadDataDir: dump });
  // warm up
  await pglite.sql`SELECT 1`;
  const { dialect } = new KyselyPGlite(pglite);
  const kysely = new Kysely<DB>({
    dialect,
    plugins: [new CamelCasePlugin()],
  });

  const originalDestroy = kysely.destroy.bind(kysely);
  kysely.destroy = async () => {
    if (isDestroyed) return;
    isDestroyed = true;
    const destroyTime = performance.now();
    await originalDestroy().catch(() => undefined);
    await pglite.close().catch(() => undefined);
    console.log(
      `Database destroyed: ${Math.round(performance.now() - destroyTime)}ms`
    );
  };

  console.log(`Database initialized: ${Math.round(performance.now() - now)}ms`);

  return kysely;
}
