const pool = require('../config/db');
const { sendMail } = require('../config/email');

async function notify(userId, type, title, message, link) {
  try {
    await pool.query('INSERT INTO notifications (user_id, type, title, message, link) VALUES (?,?,?,?,?)',
      [userId, type, title, message, link || null]);
  } catch (e) { console.error('Notify error:', e.message); }
}

async function onTicketCreated(ticket, creatorName) {
  if (ticket.assigned_to) {
    const [a] = await pool.query('SELECT name, email FROM users WHERE id=?', [ticket.assigned_to]);
    if (a.length) {
      await notify(ticket.assigned_to, 'ticket_assigned', `Nuevo ticket #${ticket.id}`, `${creatorName} creó: "${ticket.subject}"`, `/tickets/${ticket.id}`);
      sendMail(a[0].email, `[Ticket #${ticket.id}] ${ticket.subject}`,
        `<h3>Nuevo ticket asignado</h3><p><b>De:</b> ${creatorName}</p><p><b>Asunto:</b> ${ticket.subject}</p><p><b>Prioridad:</b> ${ticket.priority}</p><p>${ticket.description}</p>`);
    }
  }
  const [admins] = await pool.query('SELECT id FROM users WHERE role="admin" AND id!=?', [ticket.created_by]);
  for (const ad of admins) {
    await notify(ad.id, 'ticket_created', `Nuevo ticket #${ticket.id}`, `${creatorName}: "${ticket.subject}"`, `/tickets/${ticket.id}`);
  }
}

async function onStatusChange(ticket, changerName, oldStatus, newStatus) {
  const [cr] = await pool.query('SELECT name, email FROM users WHERE id=?', [ticket.created_by]);
  if (cr.length) {
    await notify(ticket.created_by, 'ticket_updated', `Ticket #${ticket.id} actualizado`, `${changerName} cambió estado a "${newStatus}"`, `/tickets/${ticket.id}`);
    sendMail(cr[0].email, `[Ticket #${ticket.id}] Estado: ${newStatus}`,
      `<h3>Tu ticket fue actualizado</h3><p><b>Asunto:</b> ${ticket.subject}</p><p><b>Anterior:</b> ${oldStatus}</p><p><b>Nuevo:</b> ${newStatus}</p>`);
  }
}

async function onNewComment(ticketId, commenterName, commenterId) {
  const [t] = await pool.query('SELECT id, subject, created_by, assigned_to FROM tickets WHERE id=?', [ticketId]);
  if (!t.length) return;
  const tk = t[0];
  const toNotify = new Set();
  if (tk.created_by !== commenterId) toNotify.add(tk.created_by);
  if (tk.assigned_to && tk.assigned_to !== commenterId) toNotify.add(tk.assigned_to);
  for (const uid of toNotify) {
    await notify(uid, 'ticket_comment', `Comentario en ticket #${ticketId}`, `${commenterName} comentó en "${tk.subject}"`, `/tickets/${ticketId}`);
  }
}

module.exports = { notify, onTicketCreated, onStatusChange, onNewComment };
