import { Router, Request, Response } from 'express';
import rateLimit from 'express-rate-limit';
import { pool } from '../db';

const router = Router();

const pvLimiter = rateLimit({
  windowMs: 60 * 1000,
  max: 60,
  standardHeaders: false,
  legacyHeaders: false,
});

router.use(pvLimiter);

function extractUserId(req: Request): string | null {
  const auth = req.headers.authorization;
  if (!auth?.startsWith('Bearer ')) return null;
  try {
    const jwt = require('jsonwebtoken');
    const decoded = jwt.verify(auth.slice(7), process.env.JWT_SECRET || '') as any;
    return decoded.userId || decoded.id || null;
  } catch {
    return null;
  }
}

// POST /api/pageviews/track
router.post('/track', async (req: Request, res: Response) => {
  try {
    const { path, referrer, visitor_id, session_id, screen_w } = req.body;
    if (!path || typeof path !== 'string') {
      res.status(200).json({ ok: true });
      return;
    }

    const userId = extractUserId(req);
    const ip = req.ip || req.socket.remoteAddress || null;
    const ua = (req.headers['user-agent'] || '').slice(0, 512);

    await pool.query(
      `INSERT INTO site_pageviews (site, path, referrer, visitor_id, session_id, user_id, ip_address, user_agent, screen_w)
       VALUES ('sportsclaw', $1, $2, $3, $4, $5, $6, $7, $8)`,
      [path.slice(0, 512), (referrer || '').slice(0, 1024) || null, visitor_id || null, session_id || null, userId, ip, ua || null, screen_w || null]
    );

    res.status(200).json({ ok: true });
  } catch (err) {
    console.error('Pageview track error:', err);
    res.status(200).json({ ok: true });
  }
});

// POST /api/pageviews/conversion
router.post('/conversion', async (req: Request, res: Response) => {
  try {
    const { event, visitor_id, session_id, data } = req.body;
    if (!event || typeof event !== 'string') {
      res.status(200).json({ ok: true });
      return;
    }

    const userId = extractUserId(req);
    const ip = req.ip || req.socket.remoteAddress || null;

    await pool.query(
      `INSERT INTO site_conversions (site, event, visitor_id, session_id, user_id, event_data, ip_address)
       VALUES ('sportsclaw', $1, $2, $3, $4, $5, $6)`,
      [event.slice(0, 64), visitor_id || null, session_id || null, userId, data ? JSON.stringify(data) : null, ip]
    );

    res.status(200).json({ ok: true });
  } catch (err) {
    console.error('Conversion track error:', err);
    res.status(200).json({ ok: true });
  }
});

export default router;
