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