import pool from '../config/db.js';

let tableChecked = false;

// Ensure analytics table exists with visitor_id column
async function ensureAnalyticsTable() {
  if (tableChecked) return;
  try {
    await pool.query(`
      CREATE TABLE IF NOT EXISTS platform_analytics (
        id BIGINT AUTO_INCREMENT PRIMARY KEY,
        event_type VARCHAR(50) NOT NULL,
        listing_id INT NULL,
        user_id INT NULL,
        visitor_id VARCHAR(64) NULL,
        ip_address VARCHAR(45) NULL,
        user_agent VARCHAR(255) NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_analytics_created_at (created_at),
        INDEX idx_analytics_event_type (event_type),
        INDEX idx_analytics_listing_id (listing_id)
      ) ENGINE=InnoDB;
    `);

    // Ensure visitor_id column exists for existing tables
    try {
      await pool.query(`ALTER TABLE platform_analytics ADD COLUMN IF NOT EXISTS visitor_id VARCHAR(64) NULL`);
      await pool.query(`CREATE INDEX IF NOT EXISTS idx_analytics_visitor_id ON platform_analytics(visitor_id)`);
    } catch (e) {}

    tableChecked = true;
  } catch (err) {
    console.error("Failed to verify platform_analytics table:", err.message);
  }
}

// Track an event (heartbeat, page_view, listing_view, call_click, website_click, directions_click, review_submit)
export async function trackEvent(req, res) {
  try {
    await ensureAnalyticsTable();

    let body = req.body;
    if (typeof body === 'string') {
      try {
        body = JSON.parse(body);
      } catch (e) {}
    }

    const { event_type, listing_id, user_id, visitor_id } = body || {};
    if (!event_type) {
      return res.status(400).json({ error: "Missing event_type" });
    }

    const ip = req.headers['x-forwarded-for']?.split(',')[0].trim() || req.socket.remoteAddress || '127.0.0.1';
    const userAgent = (req.headers['user-agent'] || '').substring(0, 250);
    const listingId = listing_id ? parseInt(listing_id, 10) : null;
    const userId = user_id ? parseInt(user_id, 10) : null;
    const visitorId = visitor_id ? String(visitor_id).substring(0, 64) : null;

    // Deduplicate rapid identical events from same visitor within 3 seconds (idempotency guard against StrictMode / double clicks)
    if (visitorId && event_type !== 'heartbeat') {
      const [existing] = await pool.query(
        `SELECT id FROM platform_analytics 
         WHERE visitor_id = ? 
           AND event_type = ? 
           AND (listing_id = ? OR (listing_id IS NULL AND ? IS NULL))
           AND created_at >= NOW() - INTERVAL 3 SECOND
         LIMIT 1`,
        [visitorId, event_type, listingId, listingId]
      );
      if (existing.length > 0) {
        return res.status(200).json({ success: true, deduped: true });
      }
    }

    await pool.query(
      `INSERT INTO platform_analytics (event_type, listing_id, user_id, visitor_id, ip_address, user_agent) VALUES (?, ?, ?, ?, ?, ?)`,
      [event_type, listingId, userId, visitorId, ip, userAgent]
    );

    return res.status(200).json({ success: true });
  } catch (err) {
    console.error("trackEvent error:", err.message);
    return res.status(200).json({ success: false, error: err.message });
  }
}
