/**
 * db/sample-report-leads.js — sample_report_leads table queries.
 * Owns: insert lead, list leads (admin).
 * Does NOT own: email delivery, auth logic, analytics events.
 */

'use strict';

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

/**
 * Record an email lead from the /sample-report page.
 * Returns the created row.
 */
async function insertSampleReportLead({ email, ip, referrer }) {
  const ins = await pool.query(
    `INSERT INTO sample_report_leads (email, ip, referrer)
     VALUES (:p1, :p2, :p3)
     RETURNING id INTO :out_id`,
    { p1: email.trim().toLowerCase(), p2: ip || null, p3: referrer || null, out_id: pool.outNumber() }
  );
  const result = await pool.query(
    `SELECT id, email, captured_at FROM sample_report_leads WHERE id = :p1`,
    { p1: ins.outBinds.out_id[0] }
  );
  return result.rows[0];
}

/**
 * Get all leads (admin use only).
 */
async function listSampleReportLeads({ limit = 100, offset = 0 } = {}) {
  const result = await pool.query(
    `SELECT id, email, captured_at, ip, referrer
     FROM sample_report_leads
     ORDER BY captured_at DESC
     OFFSET :p_offset ROWS FETCH NEXT :p_limit ROWS ONLY`,
    { p_limit: limit, p_offset: offset }
  );
  return result.rows;
}

module.exports = { insertSampleReportLead, listSampleReportLeads };
