/**
 * Dev-only echo + liveness endpoints.
 *
 * Mounted at /api/admin/dev ONLY when NODE_ENV !== 'production' (see index.js).
 * Used to smoke-test the WeeklyGovPushService against a local listener
 * before the Ministry publishes the real endpoint URL.
 *
 * Behaviour:
 *   GET  /api/admin/dev/health   → { ok, env }
 *   POST /api/admin/dev/echo     → returns { received: true, byteLength, sigValid, week }
 *                                   and writes an audit_logs row 'dev_echo_received'
 *                                   with the body summary + sent headers.
 *
 * No auth by design — the dev-only mount is the only protection. The
 * controller itself does not check NODE_ENV; the mounting site does.
 */

const express = require('express');
const crypto = require('crypto');
const router = express.Router();
const Database = require('better-sqlite3');
const path = require('path');

const dbPath = process.env.DB_PATH || path.join(__dirname, '..', '..', 'data', 'school.db');
const db = new Database(dbPath);
db.pragma('foreign_keys = ON');

const writeEchoAudit = (entry) => {
  try {
    db.prepare(`
      INSERT INTO audit_logs (action, entity_type, entity_id, new_data, ip_address, user_agent, created_at)
      VALUES ('dev_echo_received', 'gov_endpoint', 'local-echo', ?, ?, ?, datetime('now', 'localtime'))
    `).run(
      JSON.stringify(entry),
      entry.ip || null,
      entry.userAgent || null
    );
  } catch (e) {
    console.warn('[dev-echo] audit write failed:', e.message);
  }
};

router.get('/health', (req, res) => {
  res.json({ ok: true, env: process.env.NODE_ENV || 'development' });
});

router.post('/echo', (req, res) => {
  const body = req.body || {};
  const rawBody = JSON.stringify(body);
  const secret = (process.env.WEEKLY_GOV_PUSH_HMAC_SECRET || '').trim();
  const sentSig = (req.headers['x-signature'] || '').trim();

  let sigValid = null;
  if (secret) {
    const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
    sigValid = sentSig === expected;
  } else {
    // No secret configured — receiver-side verification is impossible; don't claim a result.
    sigValid = 'skipped (no WEEKLY_GOV_PUSH_HMAC_SECRET)';
  }

  const auditEntry = {
    byteLength: Buffer.byteLength(rawBody, 'utf8'),
    sentSig,
    sigValid,
    auth: req.headers.authorization || null,
    week: body.week || null,
    ip: req.ip,
    userAgent: req.headers['user-agent'] || null,
  };
  writeEchoAudit(auditEntry);

  console.log(
    '[dev-echo] received',
    auditEntry.byteLength,
    'bytes week=' + auditEntry.week,
    'sigValid=' + sigValid
  );

  res.json({
    received: true,
    byteLength: auditEntry.byteLength,
    sigValid,
    week: auditEntry.week,
  });
});

// Force a single push cycle. By default honors the idempotency guard
// (skip if lastWeek === currentWeek). Pass ?force=1 to bypass.
router.post('/run-push/now', async (req, res) => {
  try {
    const force = req.query.force === '1' || req.query.force === 'true';
    const { runOnce } = require('../services/WeeklyGovPushService');
    const result = await runOnce({ force });

    try {
      db.prepare(`
        INSERT INTO audit_logs (action, entity_type, entity_id, new_data, ip_address, user_agent, created_at)
        VALUES ('dev_run_push', 'gov_endpoint', 'manual-trigger', ?, ?, ?, datetime('now', 'localtime'))
      `).run(
        JSON.stringify({
          force,
          week: result.week || null,
          skipped: result.skipped,
          reason: result.reason || null,
          urls: (result.results || []).map((r) => r.url),
        }),
        req.ip,
        req.headers['user-agent'] || null
      );
    } catch (_) { /* audit is best-effort */ }

    console.log(
      '[dev-run-push] force=' + force,
      'skipped=' + result.skipped,
      'reason=' + (result.reason || '-'),
      'results=' + JSON.stringify(result.results || [])
    );
    res.json(result);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

module.exports = router;
