/**
 * db/page-events.js — page_events table CRUD.
 *
 * Owns: reading and writing page_events (landing page CTA click tracking).
 * Does NOT own: funnel analytics (analytics_events), user auth, billing.
 */

'use strict';

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

/**
 * Record a page event (CTA click or page view).
 * Fire-and-forget safe — never throws.
 *
 * @param {Object} opts
 * @param {string}  opts.eventType  — cta_click | page_view
 * @param {string}  opts.eventName  — e.g. hero_cta, pricing_cta, nav_signup
 * @param {string}  opts.pageUrl    — full URL path
 * @param {string}  [opts.referrer] — HTTP referrer
 * @param {string}  [opts.userAgent]— User-Agent truncated to 500 chars
 * @param {string}  [opts.ipHash]   — SHA-256 of full IP (no PII)
 * @param {string}  [opts.sessionId]— UUID session id
 */
async function trackPageEvent({ eventType, eventName, pageUrl, referrer = null, userAgent = null, ipHash = null, sessionId = null }) {
  try {
    await pool.query(
      `INSERT INTO page_events (event_type, event_name, page_url, referrer, user_agent, ip_hash, session_id, created_at)
       VALUES (:p1, :p2, :p3, :p4, :p5, :p6, :p7, CURRENT_TIMESTAMP)`,
      {
        p1: eventType,
        p2: eventName,
        p3: pageUrl ? pageUrl.slice(0, 500) : null,
        p4: referrer ? referrer.slice(0, 500) : null,
        p5: userAgent ? userAgent.slice(0, 500) : null,
        p6: ipHash || null,
        p7: sessionId || null,
      }
    );
  } catch (err) {
    console.log(JSON.stringify({ level: 'warn', msg: 'page_events.track failed', eventName, err: err.message }));
  }
}

/**
 * Daily event counts by event_name — for the admin analytics dashboard.
 * Returns rows like: { event_name, date, count }
 */
async function getDailyCounts({ from, to }) {
  const result = await pool.query(
    `SELECT
       event_name,
       TRUNC(created_at) AS "date",
       COUNT(*) AS "count"
     FROM page_events
     WHERE created_at BETWEEN :p1 AND :p2
     GROUP BY event_name, TRUNC(created_at)
     ORDER BY 2, 1`,
    { p1: pool.tstz(from), p2: pool.tstz(to) }
  );
  return result.rows;
}

/**
 * Overall totals by event_name — top-level summary.
 */
async function getTotals({ from, to }) {
  const result = await pool.query(
    `SELECT
       event_name,
       COUNT(*) AS "count",
       COUNT(DISTINCT session_id) AS unique_sessions
     FROM page_events
     WHERE created_at BETWEEN :p1 AND :p2
       AND event_type = 'cta_click'
     GROUP BY event_name
     ORDER BY 2 DESC`,
    { p1: pool.tstz(from), p2: pool.tstz(to) }
  );
  return result.rows;
}

module.exports = { trackPageEvent, getDailyCounts, getTotals };