'use strict'

const Broadcast = require('../models/Broadcast')
const { sseBroadcastTenant } = require('../services/sse')

function extractAuth(req) {
  const accountId = req.teamAccount?.accountId || req.admin?.id || null
  const tenantId  = req.tenantId || req.teamAccount?.tenantId || req.admin?.tenant_id || null
  const role      = req.admin?.role || req.teamAccount?.role || null
  return { accountId, tenantId, role }
}

class BroadcastController {
  /**
   * POST /api/admin/inbox/broadcast
   * Enviar broadcast para todos os colaboradores do tenant.
   * Restrito a owner e manager.
   */
  async send(req, res) {
    try {
      const { accountId, tenantId, role } = extractAuth(req)

      if (!accountId || !tenantId) return res.status(401).json({ error: 'Não autenticado' })
      if (role !== 'owner' && role !== 'manager') {
        return res.status(403).json({ error: 'Apenas owner ou manager podem enviar broadcasts' })
      }

      const { content } = req.body
      if (!content?.trim()) return res.status(400).json({ error: 'content obrigatório' })

      const bc = await Broadcast.send(tenantId, accountId, content.trim())
      res.json(bc)

      sseBroadcastTenant(tenantId, 'broadcast.sent', {
        id:           bc.id,
        from:         accountId,
        content:      content.trim(),
        created_at:   bc.created_at,
      })
    } catch (err) {
      console.error('[broadcast.send]', err.message)
      res.status(500).json({ error: 'Erro ao enviar broadcast' })
    }
  }

  /**
   * GET /api/admin/inbox/broadcasts
   * Histórico de broadcasts + unread_count do colaborador
   */
  async list(req, res) {
    try {
      const { accountId, tenantId } = extractAuth(req)
      if (!tenantId) return res.status(401).json({ error: 'Não autenticado' })

      const [items, unread] = await Promise.all([
        Broadcast.list(tenantId),
        accountId ? Broadcast.unreadCount(tenantId, accountId) : Promise.resolve(0),
      ])
      res.json({ items, unread_count: unread })
    } catch (err) {
      console.error('[broadcast.list]', err.message)
      res.status(500).json({ error: 'Erro ao listar broadcasts' })
    }
  }

  /**
   * POST /api/admin/inbox/broadcasts/seen
   * Marcar todos os broadcasts como vistos
   */
  async markSeen(req, res) {
    try {
      const { accountId, tenantId } = extractAuth(req)
      if (!accountId || !tenantId) return res.status(401).json({ error: 'Não autenticado' })
      await Broadcast.markSeen(tenantId, accountId)
      res.json({ ok: true })
    } catch (err) {
      console.error('[broadcast.markSeen]', err.message)
      res.status(500).json({ error: 'Erro ao marcar como visto' })
    }
  }
}

module.exports = new BroadcastController()
