import { Router } from 'express';
import { validate } from '../../middleware/validate';
import { authenticate } from '../../middleware/auth.middleware';
import { requireRole } from '../../middleware/rbac.middleware';
import { docsAnalyticsRateLimit } from '../../middleware/rate-limit';
import { docsAnalyticsService } from './docs-analytics.service';
import { trackPageViewSchema, analyticsQuerySchema } from './docs-analytics.schemas';
import { CONTENT_ROLES } from '../../utils/roles';

// --- Public Router (no auth) ---
export const docsAnalyticsPublicRouter = Router();

// Per-route CORS override: MkDocs runs on a different origin (root domain vs API subdomain)
import { env } from '../../config/env';
const DOCS_ORIGINS = new Set([
  env.DOMAIN ? `https://${env.DOMAIN}` : '',
  env.DOMAIN ? `https://docs.${env.DOMAIN}` : '',
  env.DOMAIN ? `http://${env.DOMAIN}` : '',
  env.ADMIN_URL || 'http://localhost:4003',
  'http://localhost:4003',
  'http://localhost:4004',
].filter(Boolean));
docsAnalyticsPublicRouter.use((req, res, next) => {
  const origin = req.headers.origin || '';
  if (DOCS_ORIGINS.has(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
  }
  res.setHeader('Vary', 'Origin');
  res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

// Handle preflight
docsAnalyticsPublicRouter.options('/track', (_req, res) => {
  res.sendStatus(204);
});

// POST /api/docs-analytics/track — record page view (fire-and-forget)
docsAnalyticsPublicRouter.post(
  '/track',
  docsAnalyticsRateLimit,
  validate(trackPageViewSchema),
  async (req, res) => {
    const { path, referrer, sessionHash } = req.body;
    const userAgent = req.headers['user-agent'] || undefined;
    const ipAddress = req.ip || req.socket.remoteAddress || undefined;

    // Fire-and-forget: don't await, respond immediately
    docsAnalyticsService.recordPageView({ path, referrer, sessionHash, userAgent, ipAddress }).catch(() => {});

    res.sendStatus(204);
  },
);

// --- Admin Router (auth required) ---
export const docsAnalyticsAdminRouter = Router();
docsAnalyticsAdminRouter.use(authenticate);
docsAnalyticsAdminRouter.use(requireRole(...CONTENT_ROLES));

// GET /api/docs-analytics/summary?days=30
docsAnalyticsAdminRouter.get(
  '/summary',
  validate(analyticsQuerySchema, 'query'),
  async (req, res) => {
    const days = Number(req.query.days) || 30;
    const summary = await docsAnalyticsService.getSummary(days);
    res.json(summary);
  },
);

// POST /api/docs-analytics/cleanup — manual cleanup trigger
docsAnalyticsAdminRouter.post('/cleanup', async (_req, res) => {
  const deleted = await docsAnalyticsService.cleanupOldData(90);
  res.json({ deleted });
});
