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

let cryptoKey: CryptoKey | null = null;
let rawKey: Uint8Array | null = null;

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

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

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

    case 'ENCRYPT':
      if (!cryptoKey) {
        self.postMessage({ type: 'ERROR', message: 'No key set', id });
        return;
      }
      try {
        const encrypted = await encryptData(payload, cryptoKey);
        self.postMessage({ type: 'ENCRYPTED', payload: encrypted, id });
      } catch (err) {
        self.postMessage({ type: 'ERROR', message: 'Encryption failed', id });
      }
      break;

    case 'BLIND_INDEX':
      if (!rawKey) {
        self.postMessage({ type: 'ERROR', message: 'No key set', id });
        return;
      }
      try {
        const hash = await generateBlindIndex(payload, rawKey);
        self.postMessage({ type: 'HASHED', payload: hash, id });
      } catch (err) {
        self.postMessage({ type: 'ERROR', message: 'Hashing failed', id });
      }
      break;
  }
};
