/**
 * Plugin: ext-api
 * Entry point — registra rotas REST e WS bridge ao activar.
 */
import type { PluginInstance, PluginContext } from '../../backend/src/core/types'
import { buildApiKeyAuth } from './backend/apikey-auth'
import { buildExtRoutes } from './backend/routes'
import { buildWsBridge } from './backend/ws-bridge'
import { buildWebhookDispatcher } from './backend/webhook-dispatcher'
import { WhatsAppConnectionManager } from '../../backend/src/modules/whatsapp/connection/WhatsAppConnectionManager'
import manifest from './manifest.json'

// O WhatsAppConnectionManager é um singleton instanciado no server.ts.
// O plugin precisa de uma referência a ele para enviar mensagens.
// Injectamos via globalThis como bridge temporária (sem modificar o server.ts).
// Em revisão futura pode ser passado no PluginContext.
declare global {
  // eslint-disable-next-line no-var
  var __whatsAppManager: WhatsAppConnectionManager | undefined
}

const plugin: PluginInstance = {
  manifest: manifest as any,

  async activate(ctx: PluginContext): Promise<void> {
    const { app, prisma, db, config, hooks, logger, httpServer } = ctx

    // ── REST ────────────────────────────────────────────────────────────────
    const manager = globalThis.__whatsAppManager
    if (!manager) {
      logger.warn('[ext-api] WhatsAppConnectionManager não disponível via globalThis.__whatsAppManager — endpoints de send desativados')
    }

    const authMiddleware = buildApiKeyAuth(prisma)
    const extRouter      = buildExtRoutes(prisma, manager as WhatsAppConnectionManager, db, config, hooks)

    app.use('/api/ext/v1', authMiddleware, extRouter)
    logger.info('[ext-api] Rotas REST registradas em /api/ext/v1')

    // ── WS Bridge ───────────────────────────────────────────────────────────
    buildWsBridge(httpServer, prisma, hooks)
    logger.info('[ext-api] WS bridge ativo em /api/ext/v1/stream (x-nw-key auth)')

    // ── Webhook Dispatcher ──────────────────────────────────────────────────
    buildWebhookDispatcher(prisma, hooks)
    logger.info('[ext-api] Webhook dispatcher ativo')
  },

  async deactivate(ctx: PluginContext): Promise<void> {
    ctx.logger.warn('[ext-api] Desativado. Reinicie o servidor para remover as rotas.')
  },
}

export default plugin
