// @blocklet/sdk/lib/security shim for CF Workers
//
// Uses the same crypto chain as original Blocklet Server:
//   password = PBKDF2(BLOCKLET_APP_EK, BLOCKLET_DID, 256, 32, sha512).hex()
//   plaintext = CryptoJS.AES.decrypt(ciphertext, password)

import crypto from 'crypto';
import CryptoJS from 'crypto-js';

let _password: string | null = null;

/** Initialize with EK + DID. After this, encrypt/decrypt work identically to Blocklet Server. */
export function initSecurity(appEk: string, blockletDid: string): void {
  _password = crypto.pbkdf2Sync(appEk, blockletDid, 256, 32, 'sha512').toString('hex');
}

export function encrypt(data: string, password?: string, salt?: string): string {
  const pw = password || _password;
  if (!pw) return data;
  return CryptoJS.AES.encrypt(data, pw).toString();
}

export function decrypt(data: string, password?: string, salt?: string): string {
  const pw = password || _password;
  if (!pw || !data) return data;
  return CryptoJS.AES.decrypt(data, pw).toString(CryptoJS.enc.Utf8);
}

/**
 * Fetch EK from AUTH_SERVICE and initialize. Call once at worker startup.
 */
export async function initFromAuthService(env: {
  AUTH_SERVICE?: any;
  APP_PID?: string;
}): Promise<void> {
  const { AUTH_SERVICE, APP_PID } = env;
  if (!AUTH_SERVICE || !APP_PID) return;

  try {
    const appEk = await AUTH_SERVICE.getAppEk(APP_PID);
    if (!appEk) {
      console.warn('[Security] No APP_EK found for instance', APP_PID);
      return;
    }
    // BLOCKLET_DID = APP_PID in Blocklet Server
    initSecurity(appEk, APP_PID);
    console.log('[Security] Initialized with EK from AUTH_SERVICE');
  } catch (err: any) {
    console.error('[Security] initFromAuthService failed:', err?.message);
  }
}

export default { encrypt, decrypt, initSecurity, initFromAuthService };
