import { sql } from 'drizzle-orm'
import { type Tx } from './index.js'

/**
 * THE ENUMERATED PRIVILEGED PATHS.
 *
 * RLS has sanctioned bypasses. #33 found they were not written down anywhere,
 * and required "an explicit reviewable list of privileged paths, not just a
 * hard-to-bypass entry point." This file is that list. It should stay short,
 * and adding to it should feel like a decision.
 *
 *   1. anonymised acceptance count   reads rows owned by other retailers
 *   2. expiry recompute              runs with no actor at all
 *   3. category grant propagation    writes eligibility for split/merge
 *
 * Nothing else may use SECURITY DEFINER or bypass a policy.
 */

/**
 * 1. The anonymised acceptance count (#13 decision 2, k-floor from #14).
 *
 * The floor is on OTHERS, not on the total: a retailer who has themselves
 * accepted the document knows they are one of the accepters and would
 * otherwise subtract themselves. So the count shown to viewer R is
 * |accepters \ {R}|, displayed only when that reaches K_FLOOR.
 *
 * The number is tunable data. The subtraction rule is structure.
 */
export const K_FLOOR = 3

export async function acceptanceCountForViewer(
  tx: Tx,
  documentId: string,
  viewerOrgId: string,
): Promise<number | null> {
  const rows = await tx.execute<{ others: number }>(sql`
    SELECT count(*)::int AS others
      FROM retailer_acceptance
     WHERE document_id = ${documentId}
       AND retailer_org_id <> ${viewerOrgId}
  `)
  const others = rows[0]?.others ?? 0
  return others >= K_FLOOR ? others : null
}

/**
 * 2. Expiry recompute. Called only from the scheduler (src/scheduler).
 *
 * Never entitlement-gated. #20 decision 3: if this were gated, a lapsed vendor
 * would stay qualified forever on stale certificates — a retailer awarding
 * against an expired policy because a third party stopped paying us.
 */
export const EXPIRY_RECOMPUTE = 'privileged:expiry-recompute' as const

/**
 * 3. Category grant propagation (#31 decision 3). A split propagates to every
 * successor; a merge only to the intersection. Event-stamped writes, never
 * read-time derivation, and never a silent revocation.
 */
export const GRANT_PROPAGATION = 'privileged:grant-propagation' as const
