import { eq, and, desc } from "drizzle-orm"; import type { Database } from "../client.js"; import { commands } from "../schema/index.js"; import { DEFAULT_TENANT_ID } from "@opentrust/shared"; export function commandQueries(db: Database) { return { async create(data: { agentId: string; type: string; payload?: Record; tenantId?: string; }) { const now = new Date().toISOString(); const tenantId = data.tenantId ?? DEFAULT_TENANT_ID; await db.insert(commands).values({ tenantId, agentId: data.agentId, type: data.type, payload: data.payload ?? null, status: "pending", createdAt: now, updatedAt: now, }); }, async findPending(agentId: string, tenantId: string = DEFAULT_TENANT_ID) { return db .select() .from(commands) .where( and( eq(commands.tenantId, tenantId), eq(commands.agentId, agentId), eq(commands.status, "pending"), ), ) .orderBy(commands.createdAt); }, async findByAgent(agentId: string, tenantId: string = DEFAULT_TENANT_ID, limit = 50) { return db .select() .from(commands) .where( and( eq(commands.tenantId, tenantId), eq(commands.agentId, agentId), ), ) .orderBy(desc(commands.createdAt)) .limit(limit); }, async ack(id: string, status: "running" | "completed" | "failed", result?: Record) { await db .update(commands) .set({ status, result: result ?? null, updatedAt: new Date().toISOString(), }) .where(eq(commands.id, id)); }, }; }