'use strict'

const { query } = require('../database/postgres')

const whatsappController = {
  async getLogs(req, res) {
    try {
      // Busca os logs de disparos unindo com o nome do usuário se disponível
      const logs = await query(`
        SELECT 
          l.*, 
          u.nome as user_name,
          u.telefone as user_phone
        FROM whatsapp_logs l
        LEFT JOIN users u ON l.user_cpf = u.cpf
        ORDER BY l.created_at DESC
        LIMIT 100
      `)
      
      // Mapeia para o formato que o React espera
      const formatted = logs.map(log => ({
        id: log.id,
        status: log.status, // sent, failed, pending
        type: log.message_type || 'notification',
        payload: log.payload || {},
        created_at: log.created_at,
        user: {
          name: log.user_name || 'Sistema',
          phone: log.user_phone || log.phone_target || '-'
        }
      }))

      return res.json(formatted)
    } catch (error) {
      console.error('Erro ao buscar logs do WhatsApp:', error)
      return res.status(500).json({ error: 'Erro interno' })
    }
  }
}

module.exports = whatsappController
