// Recipe stats route (SDD section 7.1) — success/failure counters per recipe.
// cypher-executor calls POST /recipe-stats/record after each recipe HTTP call;
// submission reads GET /recipe-stats/:canonical_id as the "proof" for no-verify submit.
import { Hono } from 'hono';
import type { Bindings } from '../types';
import { recordRecipeResult, getRecipeStat } from '../actions/recipe-stat';

export const recipeStatRoutes = new Hono<{ Bindings: Bindings }>();

// POST /recipe-stats/record — { canonical_id, ok, at } (at = epoch ms, passed in by caller)
recipeStatRoutes.post('/record', async (c) => {
  const body = await c.req.json().catch(() => null);
  if (!body || !body.canonical_id || typeof body.ok !== 'boolean') {
    return c.json({ success: false, error: 'canonical_id and ok(boolean) required' }, 400);
  }
  const at = typeof body.at === 'number' ? body.at : 0;
  const stat = await recordRecipeResult(c.env.DB, body.canonical_id, body.ok, at);
  return c.json({ success: true, stat });
});

// GET /recipe-stats/:canonical_id
recipeStatRoutes.get('/:canonical_id', async (c) => {
  const stat = await getRecipeStat(c.env.DB, c.req.param('canonical_id'));
  return c.json({ success: true, stat });
});
