/**
 * Authorisation for reads.
 *
 * The write path has had one chokepoint since F2 — `executeMutation` — and
 * reads had none. Every GET was "any authenticated member", so a research
 * contractor and a demand lead saw supplier cost per GPU-hour, break-even
 * price and the full negotiated terms of every contract identically. For a
 * company whose margin is the product, that was the hole that mattered.
 *
 * This is the reading half of the same chokepoint. It is thin on purpose:
 * capability in, middleware out, and the AuthError it throws is mapped to HTTP
 * by `app.onError` exactly as the write path's is, so a read denial and a write
 * denial are indistinguishable in shape to a client.
 *
 * `growth.ts` had the shape of this already but keyed on API-key *scope*, which
 * answers "is this credential allowed to read anything?" and not "is this
 * person allowed to read *this*". Scope is a property of the credential; the
 * capability is a property of the person. Both are checked here.
 */
import type { ReadCapability } from '@pig/core';
import type { MiddlewareHandler } from 'hono';
import { requireReadCapability } from './auth';
import type { ApiEnv } from './mutation';

export function readGuard(capability: ReadCapability): MiddlewareHandler<ApiEnv> {
  return async (context, next) => {
    requireReadCapability(context.get('principal'), capability);
    await next();
  };
}
