/**
 * db/email-log.js — append-only audit log of every outbound email.
 *
 * Owns: email_log table writes and reads.
 * Does NOT own: sending emails (see services/hc-completion-email.js).
 */

'use strict';

const pool = require('./index');

/**
 * Append an email send record.
 * @param {object} params
 * @param {number|null} params.userId
 * @param {string}      params.userEmail
 * @param {string}      params.template  — e.g. 'hc_completion'
 * @param {number|null} params.hcId      — health_check id if applicable
 * @param {string}      params.status    — 'sent' | 'failed' | 'suppressed'
 * @param {string|null} params.errorMessage
 * @param {string|null} params.postmarkMessageId — response message_id if any
 * @returns {Promise<number>} inserted row id
 */
async function logEmail({ userId, userEmail, template, hcId, status, errorMessage, postmarkMessageId }) {
  const ins = await pool.query(
    `INSERT INTO email_log (user_id, user_email, template, hc_id, status, error_message, postmark_message_id)
     VALUES (:p1, :p2, :p3, :p4, :p5, :p6, :p7)
     RETURNING id INTO :out_id`,
    { p1: userId ?? null, p2: userEmail, p3: template, p4: hcId ?? null, p5: status,
      p6: errorMessage ?? null, p7: postmarkMessageId ?? null, out_id: pool.outNumber() }
  );
  return ins.outBinds.out_id[0];
}

/**
 * Get recent email log rows for a user (admin view).
 * @param {number} userId
 * @param {number} [limit=50]
 */
async function getEmailLogForUser(userId, limit = 50) {
  const result = await pool.query(
    `SELECT id, user_email, template, hc_id, status, error_message, postmark_message_id, sent_at
     FROM email_log
     WHERE user_id = :p1
     ORDER BY sent_at DESC
     FETCH FIRST :p2 ROWS ONLY`,
    { p1: userId, p2: limit }
  );
  return result.rows;
}

module.exports = { logEmail, getEmailLogForUser };
