import { mapRuntimeEvent } from "../internal/rowMappers.js";
import { clampLimit, decodeRuntimeEventCursor, encodeRuntimeEventCursor, } from "../internal/cursors.js";
export class RuntimeEventRepository {
    #db;
    constructor(db) {
        this.#db = db;
    }
    appendRuntimeEvent(input) {
        const now = new Date().toISOString();
        const metadataJson = JSON.stringify(input.metadata ?? {});
        this.#db
            .prepare(`INSERT INTO runtime_events
           (id, run_id, runtime_session_id, source, type, occurred_at, title, description, tone, metadata_json, created_at)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
            .run(input.id, input.runId ?? null, input.runtimeSessionId ?? null, input.source, input.type, input.occurredAt, input.title, input.description, input.tone, metadataJson, now);
        return this.getRuntimeEvent(input.id);
    }
    listRuntimeEventsForRun(runId, options = {}) {
        const limit = clampLimit(options.limit ?? 50);
        const cursor = decodeRuntimeEventCursor(options.cursor);
        const rows = cursor
            ? this.#db
                .prepare(`SELECT id, run_id, runtime_session_id, source, type, occurred_at, title, description, tone, metadata_json, created_at
             FROM runtime_events
             WHERE run_id = ? AND (occurred_at > ? OR (occurred_at = ? AND id > ?))
             ORDER BY occurred_at ASC, id ASC
             LIMIT ?`)
                .all(runId, cursor.occurredAt, cursor.occurredAt, cursor.id, limit + 1)
            : this.#db
                .prepare(`SELECT id, run_id, runtime_session_id, source, type, occurred_at, title, description, tone, metadata_json, created_at
             FROM runtime_events
             WHERE run_id = ?
             ORDER BY occurred_at ASC, id ASC
             LIMIT ?`)
                .all(runId, limit + 1);
        const mapped = rows.map(mapRuntimeEvent);
        const events = mapped.slice(0, limit);
        const last = events.at(-1);
        return {
            events,
            ...(mapped.length > limit && last
                ? { nextCursor: encodeRuntimeEventCursor(last) }
                : {}),
        };
    }
    getRuntimeEvent(id) {
        const event = this.#db
            .prepare(`SELECT id, run_id, runtime_session_id, source, type, occurred_at, title, description, tone, metadata_json, created_at
         FROM runtime_events
         WHERE id = ?`)
            .get(id);
        return mapRuntimeEvent(event);
    }
}
