import { browser } from "$app/environment";
import type { Dexie, Table } from "dexie";
import { type Writable, writable } from "svelte/store";

export function hexToBytes(hex: string): Uint8Array {
  const bytes = new Uint8Array(hex.length / 2);
  for (let i = 0; i < hex.length; i += 2) {
    bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
  }
  return bytes;
}

export function bytesToHex(bytes: Uint8Array): string {
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(
    "",
  );
}

export interface MetaEntry {
  key: string;
  value: string;
}

export function persistentDbWritable<T, DB extends Dexie>(
  key: string,
  initial: T,
  db: DB & { meta: Table<MetaEntry, string> },
): Writable<T> {
  const store = writable<T>(initial);

  if (browser) {
    (async () => {
      try {
        const entry = await db.meta.get(key);
        if (entry) {
          store.set(JSON.parse(entry.value));
        } else {
          const raw = localStorage.getItem(key);
          if (raw !== null) {
            store.set(JSON.parse(raw));
            await db.meta.put({ key, value: raw });
            localStorage.removeItem(key);
          }
        }
      } catch (err) {
        console.error(`NWC store load error for ${key}`, err);
      }
    })();

    store.subscribe(async (value) => {
      try {
        await db.meta.put({ key, value: JSON.stringify(value) });
      } catch (err) {
        console.error(`NWC store persist error for ${key}`, err);
      }
    });
  }

  return store;
}
