import {
  cacheEntries
} from "./chunk-FASRXRX5.js";
import {
  CACHE_DEFAULT_TTL
} from "./chunk-L6FTY45T.js";
import {
  DRIZZLE
} from "./chunk-U64T4YZE.js";
import {
  __decorateClass,
  __decorateParam
} from "./chunk-2E224ZSN.js";

// runtime/subsystems/cache/cache.drizzle-backend.ts
import { Injectable, Inject, Optional } from "@nestjs/common";
import { gt, or, like, sql, eq } from "drizzle-orm";
var CLEANUP_INTERVAL_MS = 5 * 60 * 1e3;
var DrizzleCacheService = class {
  constructor(db, defaultTtl = null) {
    this.db = db;
    this.defaultTtl = defaultTtl;
  }
  db;
  defaultTtl;
  cleanupTimer = null;
  /** In-flight getOrSet promises — keyed by cache key to deduplicate stampedes. */
  inflight = /* @__PURE__ */ new Map();
  async onModuleInit() {
    this.cleanupTimer = setInterval(() => {
      void this.deleteExpired();
    }, CLEANUP_INTERVAL_MS);
  }
  async onModuleDestroy() {
    if (this.cleanupTimer !== null) {
      clearInterval(this.cleanupTimer);
      this.cleanupTimer = null;
    }
  }
  async get(key) {
    try {
      const rows = await this.db.select().from(cacheEntries).where(
        sql`${cacheEntries.key} = ${key} AND (${cacheEntries.expiresAt} IS NULL OR ${cacheEntries.expiresAt} > now())`
      ).limit(1);
      if (rows.length === 0) return null;
      return rows[0].value;
    } catch {
      return null;
    }
  }
  async set(key, value, ttlSeconds) {
    const effectiveTtl = ttlSeconds ?? this.defaultTtl ?? null;
    const expiresAt = effectiveTtl !== null ? new Date(Date.now() + effectiveTtl * 1e3) : null;
    const jsonValue = value;
    await this.db.insert(cacheEntries).values({ key, value: jsonValue, expiresAt }).onConflictDoUpdate({
      target: cacheEntries.key,
      set: { value: jsonValue, expiresAt }
    });
  }
  async delete(key) {
    await this.db.delete(cacheEntries).where(eq(cacheEntries.key, key));
  }
  async invalidateByPrefix(prefix) {
    const escaped = prefix.replace(/%/g, "\\%").replace(/_/g, "\\_");
    const result = await this.db.delete(cacheEntries).where(like(cacheEntries.key, `${escaped}%`)).returning({ key: cacheEntries.key });
    return result.length;
  }
  async has(key) {
    try {
      const result = await this.get(key);
      return result !== null;
    } catch {
      return false;
    }
  }
  async getOrSet(key, factory, ttlSeconds) {
    const cached = await this.get(key);
    if (cached !== null) return cached;
    const existing = this.inflight.get(key);
    if (existing !== void 0) return existing;
    const promise = factory().then(async (value) => {
      await this.set(key, value, ttlSeconds);
      return value;
    }).finally(() => {
      this.inflight.delete(key);
    });
    this.inflight.set(key, promise);
    return promise;
  }
  /** Remove all expired entries. Called by the cleanup timer. */
  async deleteExpired() {
    try {
      await this.db.delete(cacheEntries).where(
        or(
          gt(sql`now()`, cacheEntries.expiresAt)
        )
      );
    } catch {
    }
  }
};
DrizzleCacheService = __decorateClass([
  Injectable(),
  __decorateParam(0, Inject(DRIZZLE)),
  __decorateParam(1, Optional()),
  __decorateParam(1, Inject(CACHE_DEFAULT_TTL))
], DrizzleCacheService);

export {
  DrizzleCacheService
};
//# sourceMappingURL=chunk-T6C4LFLC.js.map