import { i as encodeCursor, n as clampLimit, r as decodeCursor, t as deriveStored } from "../derive-CA4PI3P5.js";
import { and, desc, eq, lt, or } from "drizzle-orm";
import { bigint, bigserial, index, jsonb, pgTable, text } from "drizzle-orm/pg-core";
//#region src/querier/table.ts
const recordStoreTable = pgTable("record_store", {
	seq: bigserial("seq", { mode: "number" }).primaryKey(),
	id: text("id").notNull(),
	createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull(),
	record: jsonb("record").notNull()
}, (table) => [index("record_store_created_at_ms_seq_idx").on(desc(table.createdAtMs), desc(table.seq))]);
const recordStoreSchema = { recordStore: recordStoreTable };
//#endregion
//#region src/querier/index.ts
function rowToStored(row) {
	return {
		id: row.id,
		createdAt: new Date(row.createdAtMs).toISOString(),
		record: row.record
	};
}
function snapshotStored(stored) {
	return {
		id: stored.id,
		createdAt: stored.createdAt,
		record: JSON.parse(JSON.stringify(stored.record))
	};
}
function makeQuerierRecordStore(db, table = recordStoreTable, opts = {}) {
	const now = opts.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
	const makeId = opts.makeId ?? (() => crypto.randomUUID());
	return {
		async append(record) {
			const derived = deriveStored(record, now, makeId);
			const [row] = await db.insert(table).values({
				id: derived.id,
				createdAtMs: derived.createdAtMs,
				record: derived.record
			}).returning();
			if (!row) throw new Error("makeQuerierRecordStore.append: insert returned no row");
			return snapshotStored({
				id: row.id,
				createdAt: derived.createdAt,
				record: row.record
			});
		},
		async list(filter = {}) {
			const limit = clampLimit(filter.limit);
			const conditions = [];
			if (filter.cursor !== void 0) {
				const cursor = decodeCursor(filter.cursor);
				conditions.push(or(lt(table.createdAtMs, cursor.createdAtMs), and(eq(table.createdAtMs, cursor.createdAtMs), lt(table.seq, cursor.seq))));
			}
			const whereClause = conditions.length > 0 ? and(...conditions) : void 0;
			const rows = await db.select().from(table).where(whereClause).orderBy(desc(table.createdAtMs), desc(table.seq)).limit(limit + 1);
			if (rows.length <= limit) return {
				items: rows.map((row) => snapshotStored(rowToStored(row))),
				nextCursor: null
			};
			const kept = rows.slice(0, limit);
			const last = kept[kept.length - 1];
			return {
				items: kept.map((row) => snapshotStored(rowToStored(row))),
				nextCursor: encodeCursor({
					createdAtMs: last.createdAtMs,
					seq: last.seq
				})
			};
		}
	};
}
//#endregion
export { makeQuerierRecordStore, recordStoreSchema, recordStoreTable };
