/**
 * 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 result = await pool.query(
    `INSERT INTO self_hosted_download_leads
       (email, downloaded_version, ip_hash, referrer, utm_source, utm_medium, utm_campaign)
     VALUES ($1, $2, $3, $4, $5, $6, $7)
     RETURNING id, email, created_at`,
    [
      email.trim().toLowerCase(),
      downloadedVersion || null,
      ipHash            || null,
      referrer          || null,
      utmSource         || null,
      utmMedium         || null,
      utmCampaign       || null,
    ]
  );
  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
     LIMIT $1 OFFSET $2`,
    [limit, offset]
  );
  return result.rows;
}

module.exports = { insertDownloadLead, listDownloadLeads };
