export interface CodeExecuteInput {
  script: string;
  mode?: 'runOnceForAll' | 'runOnceForEach';
  timeout?: number;
  data?: any;
  items?: any[];
}

export interface CodeExecuteOutput {
  result: any;
}

/**
 * Execute custom JavaScript code in a sandboxed environment.
 * Uses Node.js vm module for basic isolation.
 * For production, consider isolated-vm for stronger sandboxing.
 */
export async function codeExecute(input: CodeExecuteInput): Promise<CodeExecuteOutput> {
  const { script, mode = 'runOnceForAll', timeout = 5000, data, items } = input;
  const vm = await import('vm');

  if (mode === 'runOnceForEach' && Array.isArray(items)) {
    const results: any[] = [];
    for (const item of items) {
      const sandbox = {
        item,
        data,
        console: { log: () => {} },
        result: undefined as any,
      };
      const context = vm.createContext(sandbox);
      const wrappedScript = new vm.Script(`result = (function() { ${script} })()`);
      wrappedScript.runInContext(context, { timeout });
      results.push(sandbox.result);
    }
    return { result: results };
  }

  // runOnceForAll
  const sandbox = {
    data,
    items: items || [],
    console: { log: () => {} },
    result: undefined as any,
  };
  const context = vm.createContext(sandbox);
  const wrappedScript = new vm.Script(`result = (function() { ${script} })()`);
  wrappedScript.runInContext(context, { timeout });

  return { result: sandbox.result };
}
