import { Router, Request, Response } from 'express';
import rateLimit from 'express-rate-limit';
import pool from '../db';
import { getAuthPayloadFromRequest } from '../middleware/auth';
import { trackTikTokWebEvent } from '../services/tiktok';

const router = Router();
const FRONTEND_URL = process.env.FRONTEND_URL || 'https://rainmakersports.app';

const pvLimiter = rateLimit({
  windowMs: 60 * 1000,
  max: 60,
  standardHeaders: false,
  legacyHeaders: false,
  handler: (_req, res) => {
    res.status(200).json({ ok: true, rate_limited: true });
  },
});

router.use(pvLimiter);

async function extractUserId(req: Request): Promise<string | null> {
  const authPayload = await getAuthPayloadFromRequest(req);
  return authPayload?.userId || null;
}

function getCookieValue(req: Request, key: string): string | null {
  const value = req.cookies?.[key];
  return typeof value === 'string' && value.trim() ? value.trim() : null;
}

function normalizeText(value: unknown, maxLength: number): string | null {
  if (typeof value !== 'string') return null;
  const normalized = value.trim();
  if (!normalized) return null;
  return normalized.slice(0, maxLength);
}

function buildPageUrl(path: string): string | null {
  const normalized = normalizeText(path, 2048);
  if (!normalized) return null;
  if (/^https?:\/\//i.test(normalized)) return normalized;
  if (normalized.startsWith('/')) return `${FRONTEND_URL.replace(/\/$/, '')}${normalized}`;
  return `${FRONTEND_URL.replace(/\/$/, '')}/${normalized.replace(/^\/+/, '')}`;
}

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

    const userId = (await extractUserId(req)) || (typeof user_id === 'string' ? user_id : null);
    const ip = req.ip || req.socket.remoteAddress || null;
    const ua = (req.headers['user-agent'] || '').slice(0, 512);
    const safeAttribution = attribution && typeof attribution === 'object'
      ? attribution as Record<string, unknown>
      : null;

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

    if (req.cookies?.rm_cookie_consent === 'accepted') {
      trackTikTokWebEvent({
        event: 'PageView',
        externalId: userId || normalizeText(visitor_id, 256) || normalizeText(session_id, 256),
        ip,
        referrer: normalizeText(referrer, 2048),
        ttclid: normalizeText(safeAttribution?.ttclid, 512) || getCookieValue(req, 'rm_ttclid'),
        ttp: getCookieValue(req, '_ttp'),
        url: buildPageUrl(path),
        userAgent: ua || null,
      }).catch((err) => {
        console.error('TikTok pageview tracking failed (non-blocking):', err);
      });
    }

    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, user_id, data } = req.body;
    if (!event || typeof event !== 'string') {
      res.status(200).json({ ok: true });
      return;
    }

    const userId = (await extractUserId(req)) || (typeof user_id === 'string' ? user_id : null);
    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 ('rainmaker', $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;
