import { Router } from 'express'
import { pluginRegistry } from '../../core/plugin-registry'
import { pluginConfig } from '../../core/plugin-config'
import { storageProvider } from '../../core/StorageProvider'

/**
 * Rotas de gerenciamento de plugins — exclusivo admin.
 * Montado em /api/admin/plugins pelo server.ts via adminRouter.
 */
export const pluginsRouter = Router()

// GET /api/admin/plugins — lista todos os plugins com status e config atual
pluginsRouter.get('/', (_req, res) => {
  const plugins = pluginRegistry.list().map((entry) => ({
    name: entry.name,
    displayName: entry.manifest.displayName,
    version: entry.manifest.version,
    description: entry.manifest.description,
    author: entry.manifest.author,
    category: entry.manifest.category,
    active: entry.active,
    canDisable: entry.manifest.canDisable,
    dependencies: entry.manifest.dependencies,
    configSchema: entry.manifest.configSchema ?? [],
    config: pluginConfig.get(entry.name),
    hooks: entry.manifest.hooks ?? { subscribes: [], emits: [] },
  }))

  res.json(plugins)
})

// POST /api/admin/plugins/:name/enable — ativa plugin
pluginsRouter.post('/:name/enable', async (req, res) => {
  const { name } = req.params
  try {
    await pluginRegistry.activate(name)
    res.json({ ok: true, message: `Plugin "${name}" ativado` })
  } catch (err: any) {
    res.status(400).json({ error: err.message })
  }
})

// POST /api/admin/plugins/:name/disable — desativa plugin (se canDisable=true)
pluginsRouter.post('/:name/disable', async (req, res) => {
  const { name } = req.params
  try {
    await pluginRegistry.deactivate(name)
    res.json({ ok: true, message: `Plugin "${name}" desativado` })
  } catch (err: any) {
    res.status(400).json({ error: err.message })
  }
})

// GET /api/admin/plugins/:name/config — retorna config atual
pluginsRouter.get('/:name/config', (req, res) => {
  const { name } = req.params
  const entry = pluginRegistry.getEntry(name)
  if (!entry) return res.status(404).json({ error: `Plugin "${name}" não encontrado` })

  res.json({
    name,
    config: pluginConfig.get(name),
    schema: entry.manifest.configSchema ?? [],
  })
})

// GET /api/admin/plugins/storage/health — retorna status detalhado do storage
pluginsRouter.get('/storage/health', async (_req, res) => {
  if (!storageProvider.isRegistered()) {
    const cfg = pluginConfig.get('UnifiedStorageProvider')
    const configured = !!(cfg.wasabiAccessKey && cfg.wasabiSecretKey && cfg.wasabiBucket)
    return res.json({
      healthy: false,
      configured,
      reason: configured ? 'needs_restart' : 'not_configured',
      message: configured
        ? 'Credenciais salvas mas o plugin ainda não foi inicializado. Reinicie o servidor ou reative o plugin.'
        : 'Wasabi não configurado. Acesse Admin > Plugins > UnifiedStorageProvider e insira as credenciais.',
    })
  }
  await storageProvider.updateHealth()
  return res.json(storageProvider.getLastHealthStatus())
})

// PUT /api/admin/plugins/:name/config — salva config e reativa plugin se necessário
pluginsRouter.put('/:name/config', async (req, res) => {
  const { name } = req.params
  const entry = pluginRegistry.getEntry(name)
  if (!entry) return res.status(404).json({ error: `Plugin "${name}" não encontrado` })

  const newConfig = req.body as Record<string, unknown>

  await pluginConfig.set(name, newConfig)

  // Reativa o plugin para aplicar a nova config imediatamente
  if (entry.active) {
    try {
      await pluginRegistry.reactivate(name)
    } catch (err: any) {
      return res.status(500).json({ error: `Config salva mas falha ao reativar: ${err.message}` })
    }
  }

  res.json({ ok: true, message: `Config do plugin "${name}" salva`, config: newConfig })
})
