import { Injectable, NotFoundException } from '@nestjs/common';
import { PluginConfig } from './plugin-config.entity';
import { PluginRepository } from './plugin.repository';

@Injectable()
export class PluginService {
  constructor(private readonly pluginRepository: PluginRepository) {}

  async executePlugin(pluginId: string, args: Record<string, any>): Promise<any> {
    // 1. 获取插件配置
    const pluginConfig = await this.pluginRepository.findOne({ where: { pluginId } });
    
    if (!pluginConfig) {
      throw new NotFoundException(`Plugin ${pluginId} not found`);
    }

    try {
      // 2. 动态加载插件模块（假设插件以npm包形式安装）
      const pluginModule = require.resolve(pluginId);
      const plugin = require(pluginModule);
      
      // 3. 验证插件接口（假设插件必须实现execute方法）
      if (typeof plugin.execute !== 'function') {
        throw new Error(`Plugin ${pluginId} missing required execute method`);
      }
      
      // 4. 执行插件并返回结果
      return await plugin.execute({
        ...args,
        config: pluginConfig.settings // 传递插件配置
      });
      
    } catch (error) {
      throw new Error(`Failed to execute plugin ${pluginId}: ${error}`);
    }
  }
}