/**
 * db/download-leads.js — self_hosted_download_leads table queries.
 * Owns: insert lead, list leads (admin).
 * Does NOT own: email delivery, auth logic, analytics events, license issuing.
 *
 * Mirrors db/sample-report-leads.js. GDPR: IP stored as SHA-256 hash only
 * (same as page_events) — never the raw address.
 */

'use strict';

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

/**
 * Record an email lead from the /download (self-hosted) page.
 * Returns the created row.
 */
async function insertDownloadLead({
  email,
  downloadedVersion,
  ipHash,
  referrer,
  utmSource,
  utmMedium,
  utmCampaign,
}) {
  const ins = await pool.query(
    `INSERT INTO self_hosted_download_leads
       (email, downloaded_version, ip_hash, referrer, utm_source, utm_medium, utm_campaign)
     VALUES (:p1, :p2, :p3, :p4, :p5, :p6, :p7)
     RETURNING id INTO :out_id`,
    {
      p1: email.trim().toLowerCase(),
      p2: downloadedVersion || null,
      p3: ipHash            || null,
      p4: referrer          || null,
      p5: utmSource         || null,
      p6: utmMedium         || null,
      p7: utmCampaign       || null,
      out_id: pool.outNumber(),
    }
  );
  const result = await pool.query(
    `SELECT id, email, created_at FROM self_hosted_download_leads WHERE id = :p1`,
    { p1: ins.outBinds.out_id[0] }
  );
  return result.rows[0];
}

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

module.exports = { insertDownloadLead, listDownloadLeads };
