import { devices, eq, type Db } from "@parking/db"; import type { FastifyBaseLogger } from "fastify"; import type { DeviceReadEvent, ReadOutcome } from "./device-events.js"; import type { ExitFlow } from "./exit-flow.js"; import type { SubscriptionFlow } from "./subscription-flow.js"; import { relayForDevice } from "./device-resolve.js"; // Routes a credential read (ticket scan / plate / card) to the right flow. A read // can mean a subscription entry/exit OR a transient exit, so we dispatch by WHAT the // credential is (decision 2026-06-15): // - matches a subscription (card/QR/bound plate) → SUBSCRIPTION flow, // - else → transient EXIT flow (open ticket session → exit, else reject+log). // // The reader is BOUND to a controller relay (config.controllerId + relay), so a read // resolves to exactly the barrier it sits at, and the direction is inherited from // that relay (see entry-exit-points.md). The resolved relay is handed to the flow so // it opens that exact barrier. An "entry" reader drives the entry side, an "exit" // reader the exit side; "both" defers to the flow's own inference (subscription: // session state; transient: exit). export class ReadDispatcher { readonly #db: Db; readonly #exit: ExitFlow; readonly #subscription: SubscriptionFlow; readonly #logger: FastifyBaseLogger; constructor(db: Db, exit: ExitFlow, subscription: SubscriptionFlow, logger: FastifyBaseLogger) { this.#db = db; this.#exit = exit; this.#subscription = subscription; this.#logger = logger; } async dispatch(e: DeviceReadEvent): Promise { const reader = this.#db.select().from(devices).where(eq(devices.id, e.deviceId)).get(); if (!reader || !reader.enabled) { return { accepted: false, reason: "read from unknown/disabled device" }; } const resolved = relayForDevice(this.#db, reader); if (!resolved) { return { accepted: false, reason: "reader not bound to a barrier (no relay to open)" }; } const sub = this.#subscription.match(e); if (sub) { return this.#subscription.run(resolved, e, sub); } // Not a subscription → transient ticket exit. An ENTRY reader can't produce a // transient exit (transient entry is the button flow, not a reader), so reject+log // rather than treat an entry scan as an exit. if (resolved.direction === "entry") { return { accepted: false, direction: "entry", reason: "entry reader: no transient entry via reader" }; } return this.#exit.handleAt(resolved, e); } }