import { sql } from "kysely";
import { MessageAccessToken } from "../data/entities.js";
const MAX_TOKEN_USE_COUNT = 25;
function getKysely(em) {
  return em.getKysely();
}
async function consumeMessageAccessToken(em, tokenId) {
  const db = getKysely(em);
  const now = /* @__PURE__ */ new Date();
  const updateResult = await db.updateTable("message_access_tokens").set({
    use_count: sql`use_count + 1`,
    used_at: now
  }).where("id", "=", tokenId).where("use_count", "<", MAX_TOKEN_USE_COUNT).where("expires_at", ">", now).executeTakeFirst();
  const consumed = Number(updateResult?.numUpdatedRows ?? 0);
  if (consumed > 0) return { ok: true };
  em.clear();
  const fresh = await em.findOne(MessageAccessToken, { id: tokenId });
  if (!fresh) return { ok: false, reason: "not_found" };
  if (fresh.expiresAt < now) return { ok: false, reason: "expired" };
  return { ok: false, reason: "exhausted" };
}
export {
  MAX_TOKEN_USE_COUNT,
  consumeMessageAccessToken
};
//# sourceMappingURL=tokenConsumption.js.map
