feat(confidence-engine): add authenticated investigation persistence

This commit is contained in:
2026-09-08 17:15:46 +01:00
parent b949eea831
commit 6dd447e56a
6 changed files with 193 additions and 3 deletions
@@ -0,0 +1,66 @@
import {
createServerSupabaseClient,
getAuthenticatedUser,
} from "@/lib/supabase/server.js";
const SCHEMA = "confidence_engine";
const TABLE = "investigations";
async function getAuthenticatedPersistenceContext() {
const user = await getAuthenticatedUser();
if (!user) return null;
return { user, supabase: createServerSupabaseClient() };
}
function throwIfDatabaseError(error) {
if (error) throw new Error("Investigation persistence request failed");
}
export async function saveInvestigation(snapshot, id = snapshot?.id) {
if (!snapshot || typeof snapshot !== "object" || !id) {
throw new Error("Investigation snapshot and id are required");
}
const context = await getAuthenticatedPersistenceContext();
if (!context) return null;
const { data, error } = await context.supabase
.schema(SCHEMA)
.from(TABLE)
.upsert({ id, user_id: context.user.id, snapshot }, { onConflict: "id" })
.select("id, snapshot, created_at, updated_at")
.single();
throwIfDatabaseError(error);
return data?.snapshot ?? null;
}
export async function loadInvestigation(id) {
if (!id) return null;
const context = await getAuthenticatedPersistenceContext();
if (!context) return null;
const { data, error } = await context.supabase
.schema(SCHEMA)
.from(TABLE)
.select("snapshot")
.eq("id", id)
.maybeSingle();
throwIfDatabaseError(error);
return data?.snapshot ?? null;
}
export async function listInvestigations() {
const context = await getAuthenticatedPersistenceContext();
if (!context) return null;
const { data, error } = await context.supabase
.schema(SCHEMA)
.from(TABLE)
.select("id, created_at, updated_at")
.order("updated_at", { ascending: false });
throwIfDatabaseError(error);
return (data ?? []).map((record) => ({
id: record.id,
createdAt: record.created_at,
updatedAt: record.updated_at,
}));
}