import { Collection } from "mongodb"; import { getDb } from "../index"; import { BackgroundToolResult, BackgroundToolResultDoc, UpsertBackgroundToolResultInput, } from "./backgroundToolResults.types"; const getBackgroundToolResultsCollection = (): Collection => { return getDb().collection("backgroundToolResults"); }; const upsertBackgroundToolResult = async ( input: UpsertBackgroundToolResultInput, ): Promise => { const collection = getBackgroundToolResultsCollection(); const now = new Date(); const ttlMs = input.ttlMs ?? 60 * 60_000; const expiredAt = new Date(now.getTime() + ttlMs); const filter = { callSid: input.callSid, toolName: input.toolName }; await collection.updateOne( filter, { $set: { result: input.result, status: input.status, updatedAt: now, expiredAt, }, $setOnInsert: { callSid: input.callSid, toolName: input.toolName, createdAt: now, }, }, { upsert: true }, ); return collection.findOne(filter); }; const findBackgroundToolResult = async ( callSid: string, toolName: string, ): Promise => { const collection = getBackgroundToolResultsCollection(); return collection.findOne({ callSid, toolName }); }; const findBackgroundToolResultsByCallSid = async ( callSid: string, ): Promise => { const collection = getBackgroundToolResultsCollection(); return collection.find({ callSid }).sort({ createdAt: 1 }).toArray(); }; export { getBackgroundToolResultsCollection, upsertBackgroundToolResult, findBackgroundToolResult, findBackgroundToolResultsByCallSid, };