import { dragonfly } from '../infra/cache/dragonfly'
import { logger as rootLogger } from '../config/logger'

const KEY_PREFIX = 'plugin:config:'
// Config de plugins não expira — TTL longo (1 ano)
const TTL_SECONDS = 365 * 24 * 3600

/**
 * Config store para plugins, backed por DragonflyDB.
 * get() usa cache in-memory para evitar round-trips no hot-path.
 * set() persiste no Dragonfly e invalida o cache local.
 */
export class PluginConfigStore {
  private cache = new Map<string, Record<string, unknown>>()

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  /** Lê config de um plugin. Retorna {} se não houver config salva. */
  get(pluginName: string): Record<string, any> {
    return this.cache.get(pluginName) ?? {}
  }

  /** Persiste config no Dragonfly e atualiza cache local. */
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  async set(pluginName: string, config: Record<string, any>): Promise<void> {
    this.cache.set(pluginName, config)
    await dragonfly.setJson(`${KEY_PREFIX}${pluginName}`, config, TTL_SECONDS)
    rootLogger.debug({ pluginName }, '[PluginConfig] Config salva')
  }

  /** Carrega todas as configs do Dragonfly para o cache local no boot. */
  async loadAll(pluginNames: string[]): Promise<void> {
    await Promise.all(
      pluginNames.map(async (name) => {
        const stored = await dragonfly.getJson<Record<string, unknown>>(`${KEY_PREFIX}${name}`)
        if (stored) {
          this.cache.set(name, stored)
          rootLogger.debug({ name }, '[PluginConfig] Config carregada do Dragonfly')
        }
      }),
    )
  }

  /** Retorna config de todos os plugins (para a API admin). */
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  getAllCached(): Record<string, Record<string, any>> {
    const result: Record<string, Record<string, any>> = {}
    for (const [name, config] of this.cache.entries()) {
      result[name] = config
    }
    return result
  }
}

export const pluginConfig = new PluginConfigStore()
