import { bytesToHex, hexToBytes } from '@noble/ciphers/utils';
import { nip19 } from '@nostr/tools';
import type { NPub } from '@nostr/tools/nip19';
import { bech32m } from '@scure/base';

export function generateInvite(ccn: NPub, invite: string) {
  const npubHex = nip19.decode<'npub'>(ccn).data;
  const combinedBytes = bech32m.toWords(new Uint8Array([...hexToBytes(npubHex), ...hexToBytes(invite)]));
  return bech32m.encode('eveinvite', combinedBytes, false);
}

export function readInvite(invite: `${string}1${string}`) {
  const decoded = bech32m.decode(invite, false);
  if (decoded.prefix !== 'eveinvite') return false;
  const hexBytes = bech32m.fromWords(decoded.words);
  const npub = nip19.npubEncode(bytesToHex(hexBytes.slice(0, 32)));
  const inviteCode = bytesToHex(hexBytes.slice(32));
  return { npub, invite: inviteCode };
}
