import { inflate } from 'pako';

/**
 * Decodes TE obfuscated data: base64 decode -> XOR with key -> inflate -> JSON parse
 */
export function decodeTEData<T = unknown>(b64Data: string, key: string): T | null {
  try {
    const raw = Array.from(atob(b64Data), (c) => c.charCodeAt(0));
    const keyBytes = Array.from(new TextEncoder().encode(key));
    const keyLen = keyBytes.length;
    const xored = new Uint8Array(raw.map((byte, i) => byte ^ (keyBytes[i % keyLen] ?? 0)));

    return JSON.parse(inflate(xored, { to: 'string' }));
  } catch {
    return null;
  }
}
