import { bech32m } from '@scure/base';
import { read_string, read_varint } from './Uint8Array';
import { hexToBytes } from 'nostr-tools/utils';

const INVITE_VERSION = 2;

export function parseInviteCode(inviteCode: `${string}1${string}`): {
	version: number;
	startIndex: string;
	name: string;
	description: string;
	inviter: string;
	key: Uint8Array;
} {
	const decoded = bech32m.decode(inviteCode, false);
	if (decoded.prefix !== 'evelite') throw new Error('Invalid invite code');
	const inviteData = bech32m.fromWords(decoded.words);
	let offset = 0;
	const [version, bytesRead] = read_varint(inviteData, offset);
	offset += bytesRead;
	if (version !== INVITE_VERSION) throw new Error('Invalid invite version');
	const [name, nameLength] = read_string(inviteData, offset);
	offset += nameLength;
	const [description, descriptionLength] = read_string(inviteData, offset);
	offset += descriptionLength;
	const [inviter, inviterLength] = read_string(inviteData, offset);
	offset += inviterLength;
	if (inviterLength != 33) throw new Error('Invalid inviter length'); // 32 + 1
	const [key, keyLength] = read_string(inviteData, offset);
	offset += keyLength;
	if (keyLength != 33) throw new Error('Invalid invite key'); // 32 + 1
	const [startIndex, startIndexLength] = read_string(inviteData, offset);
	offset += startIndexLength;
	return { version, startIndex, name, description, inviter, key: hexToBytes(key) };
}
