import { Provide, Scope, ScopeEnum, Inject } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { DesktopOpConfigEntity } from '../entity/desktop_op_config.js';
import { SafetyGuard } from '../runtime/safety_guard.js';
import { AdapterRegistry } from '../runtime/adapters/registry.js';
import { WeixinAdapter } from '../runtime/adapters/weixin_adapter.js';

/**
 * desktop_op 启动 bootstrap — onReady 时调 ensureConfigAndLoad():
 *  1. 若 desktop_op_config 表无 id=1 行,插入默认值
 *  2. 把配置加载到 SafetyGuard
 *  3. 注册 WeixinAdapter 到 AdapterRegistry
 */
@Provide()
@Scope(ScopeEnum.Singleton)
export class DesktopOpConfigBootstrap {
  @InjectEntityModel(DesktopOpConfigEntity)
  configRepo!: Repository<DesktopOpConfigEntity>;

  @Inject()
  safetyGuard!: SafetyGuard;

  @Inject()
  adapterRegistry!: AdapterRegistry;

  @Inject()
  weixinAdapter!: WeixinAdapter;

  async ensureConfigAndLoad(): Promise<void> {
    let cfg = await this.configRepo.findOne({ where: { id: 1 } });
    if (!cfg) {
      cfg = await this.configRepo.save({
        id: 1,
        allowedApps: ['weixin'],
        extraDangerousKeys: null,
        globalPerMin: 30,
        globalPerDay: 1000,
        defaultWatermark: 'suffix',
      } as any);
    }

    // v4 防御:TypeORM JSON 字段反序列化结果可能是字符串(老数据)
    let allowedApps = cfg.allowedApps;
    if (typeof allowedApps === 'string') {
      try { allowedApps = JSON.parse(allowedApps); } catch { allowedApps = ['weixin']; }
    }
    if (!Array.isArray(allowedApps) || allowedApps.length === 0) {
      allowedApps = ['weixin'];
    }
    let extraDangerousKeys = cfg.extraDangerousKeys;
    if (typeof extraDangerousKeys === 'string') {
      try { extraDangerousKeys = JSON.parse(extraDangerousKeys); } catch { extraDangerousKeys = undefined; }
    }

    // eslint-disable-next-line no-console
    console.log('[desktop-op] config bootstrap — allowedApps=%j extraDangerousKeys=%j', allowedApps, extraDangerousKeys);

    await this.safetyGuard.loadConfig({
      allowedApps,
      extraDangerousKeys: extraDangerousKeys ?? undefined,
    });

    // v4: 注册 WeixinAdapter 到 AdapterRegistry(MVP 唯一应用适配器)
    try {
      this.adapterRegistry.register(this.weixinAdapter);
      // eslint-disable-next-line no-console
      console.log('[desktop-op] WeixinAdapter registered, available appIds=%j', this.adapterRegistry.listAppIds());
    } catch (e: any) {
      if (!String(e?.message ?? '').includes('adapter-already-registered')) throw e;
    }
  }
}
