import { Router, Request, Response } from 'express';
import { cacheMiddleware } from '../middleware/cache';
import { buildHoLiquiditySnapshot } from '../../services/omnl-ho-liquidity-snapshot';

const router = Router();

/**
 * GET /omnl/ho-liquidity-snapshot — public read-only HO nostro + reserve coverage (cached).
 * Refreshed on 30-minute operator timer; ?refresh=1 forces Fineract replay when configured.
 */
router.get('/omnl/ho-liquidity-snapshot', cacheMiddleware(30 * 60 * 1000), async (req: Request, res: Response) => {
  try {
    const forceRefresh = req.query.refresh === '1';
    const officeId = req.query.officeId != null ? Number(req.query.officeId) : undefined;
    const snapshot = await buildHoLiquiditySnapshot({
      officeId: Number.isFinite(officeId) ? officeId : undefined,
      forceRefresh,
      lineId: String(req.query.lineId || '') || undefined,
    });

    const hasCritical = snapshot.alerts.some((a) => a.severity === 'critical');
    const status = snapshot.fineractConfigured && !hasCritical ? 200 : hasCritical ? 503 : 409;

    res.setHeader('Cache-Control', 'public, max-age=300, stale-while-revalidate=900');
    res.setHeader('X-OMNL-HO-Nostro-Audit-At', snapshot.generatedAt);
    res.status(status).json(snapshot);
  } catch (e) {
    const msg = e instanceof Error ? e.message : String(e);
    res.status(500).json({ error: msg });
  }
});

export default router;
