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';

/** desktop_op 全局配置读写服务（id=1 单行模式） */
@Provide()
@Scope(ScopeEnum.Singleton)
export class DesktopOpConfigService {
  @InjectEntityModel(DesktopOpConfigEntity)
  configRepo!: Repository<DesktopOpConfigEntity>;

  /** SafetyGuard 单例，配置更新后需 reload */
  @Inject()
  safetyGuard!: SafetyGuard;

  /** 读取配置（id=1，启动时已由 bootstrap 确保存在） */
  async info(): Promise<DesktopOpConfigEntity | null> {
    return this.configRepo.findOne({ where: { id: 1 } });
  }

  /**
   * 更新配置并重新加载 SafetyGuard
   * @param body 需要更新的字段（Partial，id 强制锁定为 1）
   */
  async update(body: Partial<DesktopOpConfigEntity>): Promise<DesktopOpConfigEntity> {
    // 读取现有行（不存在则从空对象合并）
    const existing = await this.configRepo.findOne({ where: { id: 1 } });
    const merged = {
      ...(existing ?? {}),
      ...body,
      id: 1, // 强制 id=1，防止前端误传
    } as DesktopOpConfigEntity;
    // 持久化
    await this.configRepo.save(merged);
    // 通知 SafetyGuard 重新加载应用白名单和危险键配置
    await this.safetyGuard.loadConfig({
      allowedApps: merged.allowedApps,
      extraDangerousKeys: merged.extraDangerousKeys ?? undefined,
    });
    return merged;
  }
}
