import NDK, { NDKPrivateKeySigner } from '@nostr-dev-kit/ndk';
import * as nip49 from '@nostr/tools/nip49';

export const ndk = new NDK({
  explicitRelayUrls: ['ws://localhost:6942'],
  enableOutboxModel: false,
  autoConnectUserRelays: false,
  clientName: 'Arx',
  clientNip89: 'arx',
});

export async function getSigner() {
  await ndk.connect();
  if (ndk.signer) return;
  const encryptionPassphrase = localStorage.getItem('encryption_key');
  if (!encryptionPassphrase) throw new Error('Encryption passphrase not found');
  const signer = new NDKPrivateKeySigner(nip49.decrypt(localStorage.getItem('ncryptsec')!, encryptionPassphrase));
  setSigner(signer);
}

export async function getNpub() {
  await getSigner();
  const user = await ndk.signer?.user();
  if (user) return user.npub;
  throw new Error('Could not get npub');
}

export function setSigner(signer: NDKPrivateKeySigner) {
  ndk.signer = signer;
}

export async function getUserProfile(npub: string | undefined = undefined) {
  await ndk.connect();
  const npubToCheck = npub ? npub : await getNpub();
  const query = npubToCheck.startsWith('npub') ? { npub: npubToCheck } : { pubkey: npubToCheck };
  const user = ndk.getUser(query);
  await user.fetchProfile();
  return user.profile;
}
