import {
  OAuthStateError
} from "./chunk-BPARRK6F.js";
import {
  authOAuthState
} from "./chunk-NPFPZ2HO.js";

// runtime/subsystems/auth/backends/state-store.drizzle-backend.ts
import { randomBytes } from "crypto";
import { eq } from "drizzle-orm";
var DrizzleOAuthStateStore = class {
  constructor(db, opts = {}) {
    this.db = db;
    this.ttlMs = opts.ttlMs ?? 10 * 60 * 1e3;
    this.now = opts.now ?? (() => Date.now());
    this.generateToken = opts.generateToken ?? (() => randomBytes(32).toString("base64url"));
  }
  db;
  ttlMs;
  now;
  generateToken;
  async generate(record) {
    const state = this.generateToken();
    const expiresAt = new Date(this.now() + this.ttlMs);
    await this.db.insert(authOAuthState).values({
      state,
      userId: record.userId,
      redirect: record.redirect ?? null,
      expiresAt
    });
    return state;
  }
  async consume(state) {
    const rows = await this.db.delete(authOAuthState).where(eq(authOAuthState.state, state)).returning();
    const row = rows[0];
    if (!row) {
      throw new OAuthStateError(
        `OAuth state token unknown or already consumed`,
        "missing"
      );
    }
    if (row.expiresAt.getTime() <= this.now()) {
      throw new OAuthStateError(`OAuth state token expired`, "expired");
    }
    return {
      userId: row.userId,
      redirect: row.redirect ?? void 0
    };
  }
};

export {
  DrizzleOAuthStateStore
};
//# sourceMappingURL=chunk-N5OTOWTP.js.map