using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using MotoresArgentinosV2.Infrastructure.Data; using MotoresArgentinosV2.Core.Entities; using MotoresArgentinosV2.Core.Interfaces; using Microsoft.AspNetCore.Authorization; namespace MotoresArgentinosV2.API.Controllers; [Authorize] [ApiController] [Route("api/[controller]")] public class ChatController : ControllerBase { private readonly MotoresV2DbContext _context; private readonly INotificationService _notificationService; public ChatController(MotoresV2DbContext context, INotificationService notificationService) { _context = context; _notificationService = notificationService; } [HttpPost("send")] public async Task SendMessage([FromBody] ChatMessage msg) { // 1. Guardar Mensaje msg.SentAt = DateTime.UtcNow; msg.IsRead = false; _context.ChatMessages.Add(msg); await _context.SaveChangesAsync(); // 2. Notificar por Email (Con manejo de errores silencioso) try { var receiver = await _context.Users.FindAsync(msg.ReceiverID); var sender = await _context.Users.FindAsync(msg.SenderID); if (receiver != null && !string.IsNullOrEmpty(receiver.Email)) { // LÓGICA DE NOMBRE DE REMITENTE string senderDisplayName; if (sender != null && sender.UserType == 3) // 3 = ADMIN { // Caso: Moderador escribe a Usuario senderDisplayName = "Un moderador de Motores Argentinos"; } else { // Caso: Usuario responde a Moderador string name = sender?.UserName ?? "Un usuario"; senderDisplayName = $"El usuario {name}"; } await _notificationService.SendChatNotificationEmailAsync( receiver.Email, senderDisplayName, // Pasamos el nombre formateado msg.MessageText, msg.AdID); } } catch (Exception ex) { // Loguear error sin romper el flujo del chat Console.WriteLine($"Error enviando notificación de chat: {ex.Message}"); } return Ok(msg); } [HttpGet("inbox/{userId}")] public async Task GetInbox(int userId) { // Obtener todas las conversaciones donde el usuario es remitente o destinatario var messages = await _context.ChatMessages .Where(m => m.SenderID == userId || m.ReceiverID == userId) .OrderByDescending(m => m.SentAt) .ToListAsync(); return Ok(messages); } [HttpGet("conversation/{adId}/{user1Id}/{user2Id}")] public async Task GetConversation(int adId, int user1Id, int user2Id) { var messages = await _context.ChatMessages .Where(m => m.AdID == adId && ((m.SenderID == user1Id && m.ReceiverID == user2Id) || (m.SenderID == user2Id && m.ReceiverID == user1Id))) .OrderBy(m => m.SentAt) .ToListAsync(); return Ok(messages); } [HttpPost("mark-read/{messageId}")] public async Task MarkRead(int messageId) { var msg = await _context.ChatMessages.FindAsync(messageId); if (msg == null) return NotFound(); msg.IsRead = true; await _context.SaveChangesAsync(); return Ok(); } [HttpGet("unread-count/{userId}")] public async Task GetUnreadCount(int userId) { // Seguridad: Asegurarse de que el usuario que consulta es el dueño de los mensajes o un admin. var currentUserId = int.Parse(User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value ?? "0"); var isAdmin = User.IsInRole("Admin"); if (currentUserId != userId && !isAdmin) { return Forbid(); } var count = await _context.ChatMessages .CountAsync(m => m.ReceiverID == userId && !m.IsRead); return Ok(new { count }); } }