/**
 * Bump financials_version KV counter after invoice/expense mutations.
 * Used by invoice and expense route groups (reports-analytics wave C caching).
 */
import type { MiddlewareHandler } from 'hono'
import type { AppEnv } from '../types'
import { bumpFinancialsVersion } from '../lib/report-cache'

const MUTATION_METHODS = new Set(['POST', 'PATCH', 'PUT', 'DELETE'])

export const bumpFinancialsVersionOnWrite: MiddlewareHandler<AppEnv> = async (c, next) => {
  await next()

  if (!MUTATION_METHODS.has(c.req.method)) return
  if (c.res.status >= 400) return

  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) return

  c.executionCtx.waitUntil(bumpFinancialsVersion(c.env, session.tid))
}
