// crypto.worker.ts
import { importKey, decryptLog } from '../lib/crypto';

let cryptoKey: CryptoKey | null = null;

self.onmessage = async (event) => {
  const { type, payload } = event.data;

  switch (type) {
    case 'SET_KEY':
      // payload is the raw Uint8Array key
      cryptoKey = await importKey(payload);
      self.postMessage({ type: 'KEY_READY' });
      break;

    case 'DECRYPT':
      if (!cryptoKey) {
        self.postMessage({ type: 'ERROR', message: 'No key set' });
        return;
      }
      try {
        const decrypted = await decryptLog(payload, cryptoKey);
        self.postMessage({ type: 'DECRYPTED', payload: decrypted });
      } catch (err) {
        self.postMessage({ type: 'ERROR', message: 'Decryption failed' });
      }
      break;
  }
};
