/**
 * Monitoring hooks (SEO Phase 13), all optional and set through env variables:
 * - GSC_VERIFICATION → <meta name="google-site-verification"> (Google Search Console)
 * - PLAUSIBLE_DOMAIN → Plausible analytics script (no cookies; `defer`, so it never blocks rendering)
 * - every 404 page is recorded: in the `not_found_log` table (database mode) or the app log (JSON mode)
 */
import type { Request } from 'express';
import { db } from '../db/knex';
import { env } from '../config/env';
import { logger } from '../lib/logger';

const attr = (s: string) => s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');

/** Adds the verification meta and analytics script to the page template once, at start-up. */
export function withMonitoringTags(
  template: string,
  o: { gsc?: string; plausibleDomain?: string; plausibleSrc?: string } = {
    gsc: env.GSC_VERIFICATION,
    plausibleDomain: env.PLAUSIBLE_DOMAIN,
    plausibleSrc: env.PLAUSIBLE_SRC,
  },
) {
  const tags: string[] = [];
  if (o.gsc) tags.push(`<meta name="google-site-verification" content="${attr(o.gsc)}" />`);
  if (o.plausibleDomain && o.plausibleSrc)
    tags.push(`<script defer data-domain="${attr(o.plausibleDomain)}" src="${attr(o.plausibleSrc)}"></script>`);
  return tags.length ? template.replace('</head>', `    ${tags.join('\n    ')}\n  </head>`) : template;
}

/** Origin of the analytics script, for the Content-Security-Policy (null when analytics is off). */
export const analyticsOrigin = () => (env.PLAUSIBLE_DOMAIN ? new URL(env.PLAUSIBLE_SRC).origin : null);

/** Records a 404: one row per path with a hit counter, so broken links and missing medicines show up. */
export function logNotFound(req: Request, siteData = env.SITE_DATA) {
  const path = req.originalUrl.split('?')[0].slice(0, 300);
  const referrer = String(req.get('referer') ?? '').slice(0, 300) || null;
  if (siteData === 'json') {
    logger.info({ path, referrer }, 'page not found');
    return;
  }
  db('not_found_log')
    .insert({ path, referrer, hits: 1, last_seen_at: db.fn.now() })
    .onConflict('path')
    .merge({ hits: db.raw('hits + 1'), last_seen_at: db.fn.now(), ...(referrer ? { referrer } : {}) })
    .catch((err: unknown) => logger.warn({ err, path }, 'could not record 404'));
}
