import {createMiddleware} from 'hono/factory'
import {HTTPException} from 'hono/http-exception'

// e2e fault injection: a flag the /dev/network route flips so a flow can
// simulate an unreachable api mid-test — the ios simulator has no airplane
// mode (maestro's setAirplaneMode is a no-op there). the guard middleware is
// mounted on the authed routes; it can only ever fire in a dev/e2e build,
// since the /dev router that flips this 404s in production
let down = false

export const setNetworkDown = (value: boolean): void => {
  down = value
}

const isNetworkDown = (): boolean => down

// fail a request before it reaches a handler while the toggle is down. the
// mobile rpc layer translates this coded 503 into a synthetic network error,
// so the outbox exercises its true offline path (no verdict, wait for
// reconnect) rather than the server-error path (capped retries)
export const devNetworkGuard = createMiddleware(async (_c, next) => {
  if (isNetworkDown())
    throw new HTTPException(503, {message: 'network_down'})
  await next()
})
