const db  = require('../db/db');
const sse = require('../sse');

function pushNotif(user_id, type, message, link) {
  try {
    const { lastInsertRowid } = db.prepare(
      "INSERT INTO notifications (user_id, type, message, link) VALUES (?, ?, ?, ?)"
    ).run(user_id, type, message, link || null);
    sse.emit(user_id, { id: lastInsertRowid, type, message, link: link || null });
  } catch (e) { console.error('[pushNotif]', e.message); }
}

/* ── Notify all active parent links for a student ────────────────────── */
function pushParentNotif(studentId, type, message) {
  try {
    const links = db.prepare(
      'SELECT id FROM parent_links WHERE student_id = ? AND is_active = 1'
    ).all(studentId);
    const ins = db.prepare(
      'INSERT INTO parent_notifications (parent_link_id, type, message) VALUES (?, ?, ?)'
    );
    for (const link of links) ins.run(link.id, type, message);
  } catch (e) { console.error('[pushParentNotif]', e.message); }
}

module.exports = { pushNotif, pushParentNotif };
