/**
 * Secrets vault (BRD §10 connector rules): OAuth tokens and keys are stored AES-256-GCM encrypted in a separate
 * table, referenced from integrations.token_ref — never in application tables in plaintext.
 * For AWS Secrets Manager / HashiCorp Vault, replace these three functions; callers only use the reference id.
 */
import { eq } from "drizzle-orm";
import { schema, type DB } from "@/db";
import { decrypt, encrypt } from "./crypto";
import type { Credentials } from "@/connectors/types";

export async function writeSecret(db: DB, workspaceId: string | null, data: Credentials, existingRef?: string | null) {
  const ciphertext = encrypt(JSON.stringify(data));
  if (existingRef) {
    await db.update(schema.secrets).set({ ciphertext }).where(eq(schema.secrets.id, existingRef));
    return existingRef;
  }
  const [row] = await db.insert(schema.secrets).values({ workspaceId, ciphertext }).returning({ id: schema.secrets.id });
  return row!.id;
}

export async function readSecret(db: DB, ref: string): Promise<Credentials | null> {
  const row = await db.query.secrets.findFirst({ where: eq(schema.secrets.id, ref) });
  if (!row) return null;
  try {
    return JSON.parse(decrypt(row.ciphertext)) as Credentials;
  } catch {
    return null;
  }
}

export async function deleteSecret(db: DB, ref: string) {
  await db.delete(schema.secrets).where(eq(schema.secrets.id, ref));
}
