import { i as encodeCursor, n as clampLimit, r as decodeCursor, t as deriveStored } from "../derive-CA4PI3P5.js";
//#region src/d1/index.ts
function recordStoreD1TableSql(table) {
	return [`CREATE TABLE IF NOT EXISTS ${table} (seq INTEGER PRIMARY KEY AUTOINCREMENT, id text NOT NULL, created_at_ms integer NOT NULL, record text NOT NULL);`, `CREATE INDEX IF NOT EXISTS ${table}_created_at_ms_seq_idx ON ${table} (created_at_ms DESC, seq DESC);`].join("\n");
}
function rowToStored(row) {
	return {
		id: row.id,
		createdAt: new Date(row.created_at_ms).toISOString(),
		record: JSON.parse(row.record)
	};
}
function snapshotStored(stored) {
	return {
		id: stored.id,
		createdAt: stored.createdAt,
		record: JSON.parse(JSON.stringify(stored.record))
	};
}
function makeD1RecordStore(d1, table, 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 result = await d1.prepare(`INSERT INTO ${table} (id, created_at_ms, record) VALUES (?, ?, ?)`).bind(derived.id, derived.createdAtMs, JSON.stringify(derived.record)).run();
			if (result.meta.last_row_id === void 0 || result.meta.last_row_id === null) throw new Error("makeD1RecordStore.append: insert returned no last_row_id");
			return snapshotStored({
				id: derived.id,
				createdAt: derived.createdAt,
				record: derived.record
			});
		},
		async list(filter = {}) {
			const limit = clampLimit(filter.limit);
			let rows;
			if (filter.cursor !== void 0) {
				const cursor = decodeCursor(filter.cursor);
				rows = (await d1.prepare(`SELECT seq, id, created_at_ms, record FROM ${table}
             WHERE created_at_ms < ? OR (created_at_ms = ? AND seq < ?)
             ORDER BY created_at_ms DESC, seq DESC
             LIMIT ?`).bind(cursor.createdAtMs, cursor.createdAtMs, cursor.seq, limit + 1).all()).results ?? [];
			} else rows = (await d1.prepare(`SELECT seq, id, created_at_ms, record FROM ${table}
             ORDER BY created_at_ms DESC, seq DESC
             LIMIT ?`).bind(limit + 1).all()).results ?? [];
			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.created_at_ms,
					seq: last.seq
				})
			};
		}
	};
}
//#endregion
export { makeD1RecordStore, recordStoreD1TableSql };
