/**
 * GET /api/founders/count — the REAL founder-seat counter.
 *
 * TRUTH LAW: the ClaimMeter used to render a hardcoded "47 / 100 CLAIMED", then
 * a DB-profile count that showed a phantom "1" (a comped/manually-tiered account
 * with founder_pricing=true but no real payment). Security follow-up item 0: the
 * count is now Stripe's OWN truth — the number of ACTIVE subscriptions on a
 * founder price (`stripeService.countFounderSeats`), verified against
 * subscription status, never a tier/founder_pricing field a profile can set
 * without paying. Cached 5 min in Redis so we never hammer the API.
 *
 * If Stripe / the founder prices aren't configured, or any call fails, we return
 * { available: false } and the UI HIDES the counter — never a fabricated number.
 * A count of 0 is shown honestly; the truth is the feature.
 */

const express = require('express');
const stripeService = require('../services/stripeService');
const { cacheGet, cacheSet } = require('../utils/redis');

const router = express.Router();

const TOTAL = Number(process.env.FOUNDER_SEATS_TOTAL || 100);
const CACHE_KEY = 'founders:count';
const CACHE_TTL = 300; // 5 min — the founder count moves slowly

// Injectable for tests (never hits the network in the unit suite).
let _countSeats = stripeService.countFounderSeats;
let _cacheGet = cacheGet;
let _cacheSet = cacheSet;
function __setDeps({ countSeats, cacheGet: cg, cacheSet: cs } = {}) {
  _countSeats = countSeats || stripeService.countFounderSeats;
  _cacheGet = cg || cacheGet;
  _cacheSet = cs || cacheSet;
}

router.get('/count', async (req, res) => {
  // Cache first — don't recount (a Stripe API call) on every landing hit.
  try {
    const cached = await _cacheGet(CACHE_KEY);
    if (cached && typeof cached.claimed === 'number') {
      return res.json({ available: true, claimed: cached.claimed, total: TOTAL });
    }
  } catch { /* cache miss/degraded — fall through to a live count */ }

  try {
    const count = await _countSeats();
    // null = Stripe / founder prices unconfigured → hide, never a number.
    if (count == null || !Number.isFinite(Number(count))) return res.json({ available: false });
    const claimed = Math.max(0, Number(count));
    try { await _cacheSet(CACHE_KEY, { claimed }, CACHE_TTL); } catch { /* best-effort */ }
    return res.json({ available: true, claimed, total: TOTAL });
  } catch {
    return res.json({ available: false }); // any failure → hide, never fabricate
  }
});

router.__setDeps = __setDeps;
router.__internals = { TOTAL, CACHE_KEY, CACHE_TTL };
module.exports = router;
