/**
 * Which capability each read requires — the whole policy, in one table.
 *
 * It lives in a table rather than beside each handler because the question a
 * reviewer needs to answer is "who can see cost?", and that question is
 * unanswerable if the answer is spread across nine route files. Adding a GET
 * without adding a row here leaves it ungoverned, which is the failure this
 * exists to end; `read-governance.test.ts` fails when a new read path appears
 * that no row covers.
 *
 * Mounted before every other route in `createApp`, and the order is
 * load-bearing: Hono runs matched handlers in registration order, so a guard
 * registered after its handler never runs.
 */
import type { ReadCapability } from '@pig/core';
import { Hono } from 'hono';
import { readGuard } from '../lib/read-guard';
import type { ApiEnv } from '../lib/mutation';

export interface ReadRule {
  method: 'GET' | 'POST';
  path: string;
  capability: ReadCapability;
}

/**
 * `economics:read` covers anything carrying supplier cost, break-even price or
 * a margin total. `/api/capacity/match` is a POST only because a requirement
 * is too big for a query string — it returns break-even per block, so it is a
 * read and is gated as one.
 */
export const READ_RULES: readonly ReadRule[] = [
  { method: 'GET', path: '/api/capacity/availability', capability: 'economics:read' },
  { method: 'GET', path: '/api/capacity/idle', capability: 'economics:read' },
  { method: 'GET', path: '/api/capacity/margin', capability: 'economics:read' },
  { method: 'POST', path: '/api/capacity/match', capability: 'economics:read' },
  { method: 'GET', path: '/api/inventory', capability: 'economics:read' },
  { method: 'GET', path: '/api/commitments', capability: 'economics:read' },
  { method: 'GET', path: '/api/allocations', capability: 'economics:read' },
  { method: 'GET', path: '/api/dashboard', capability: 'economics:read' },

  { method: 'GET', path: '/api/accounts', capability: 'book:read' },
  { method: 'GET', path: '/api/accounts/:id', capability: 'book:read' },
  { method: 'GET', path: '/api/contacts', capability: 'book:read' },
  { method: 'GET', path: '/api/deals/demand', capability: 'book:read' },
  { method: 'GET', path: '/api/deals/supply', capability: 'book:read' },
  { method: 'GET', path: '/api/contracts', capability: 'book:read' },
  { method: 'GET', path: '/api/contracts/:id', capability: 'book:read' },
  { method: 'GET', path: '/api/growth', capability: 'book:read' },
  { method: 'GET', path: '/api/growth/accounts/:id', capability: 'book:read' },
  { method: 'GET', path: '/api/facts', capability: 'book:read' },

  { method: 'GET', path: '/api/team', capability: 'team:read' },
];

export function createReadGuardRoutes(rules: readonly ReadRule[] = READ_RULES): Hono<ApiEnv> {
  const routes = new Hono<ApiEnv>();
  for (const rule of rules) routes.on(rule.method, rule.path, readGuard(rule.capability));
  return routes;
}
