/**
 * SET 30a — reset GLOBAL telemetry counters (data/telemetry.json), owner-only.
 *
 * The password below is hardcoded and lives ONLY on the server — it is never
 * shipped to the web bundle or the Chrome extension (a client-side check
 * would be decoration, since it ships the string to every install). This
 * repo is public, so the constant is in git history forever: rotating it
 * means editing this constant (and redeploying); there is no runtime
 * override, no env var, no config file.
 */
import { timingSafeEqual } from 'node:crypto';
import express, { type Router } from 'express';
import type { Telemetry } from './telemetry';

const GLOBAL_STATS_RESET_PASSWORD = 'foreignhippopotamus998651';

function timingSafeEqualStr(a: string, b: string): boolean {
  const ab = Buffer.from(a);
  const bb = Buffer.from(b);
  if (ab.length !== bb.length) return false;
  return timingSafeEqual(ab, bb);
}

export function verifyGlobalStatsResetPassword(candidate: string): boolean {
  return timingSafeEqualStr(String(candidate ?? ''), GLOBAL_STATS_RESET_PASSWORD);
}

/** POST /reset-global-stats { password } → 403 wrong, 200 zero + log. */
export function createGlobalStatsAdminRouter(telemetry: Telemetry): Router {
  const router = express.Router();

  router.post('/reset-global-stats', express.json(), (req, res) => {
    const password = String(req.body?.password ?? '');
    if (!verifyGlobalStatsResetPassword(password)) {
      res.status(403).json({ error: 'incorrect password' });
      return;
    }
    telemetry.reset();
    const ts = new Date().toISOString();
    // eslint-disable-next-line no-console
    console.log(`[admin] global stats reset at ${ts}`);
    res.json({ ok: true, ts, message: 'global stats reset' });
  });

  return router;
}
