/**
 * Adapter credential storage helpers — system-communications-notifications.
 *
 * Wraps the `adapter_credentials` table with AES-256-GCM encrypt/decrypt
 * (delegated to `@zync/auth/crypto`) and the `tenantQuery` isolation pattern.
 *
 * `saveAdapterCredential`: upserts credentials (insert or update on conflict).
 * `loadAdapterCredential`: decrypts and returns the secret JSON string, or null.
 */
import type { Db } from '@zync/db/queries'
import {
  saveAdapterCredentialRow,
  loadAdapterCredentialRow,
} from '@zync/db/queries'
import { encryptCredential, decryptCredential } from '@zync/auth'

export async function saveAdapterCredential(
  db: Db,
  tenantId: string,
  adapterId: string,
  secretJson: string,
  metadata: Record<string, unknown>,
  encryptionKey: string,
): Promise<void> {
  const encrypted = await encryptCredential(secretJson, encryptionKey)
  await saveAdapterCredentialRow(db, {
    tenantId,
    adapterId,
    ciphertext: encrypted.ciphertext,
    iv: encrypted.iv,
    authTag: encrypted.authTag,
    metadata,
  })
}

export async function loadAdapterCredential(
  db: Db,
  tenantId: string,
  adapterId: string,
  encryptionKey: string,
): Promise<string | null> {
  const row = await loadAdapterCredentialRow(db, tenantId, adapterId)
  if (!row) return null

  return decryptCredential(
    {
      ciphertext: row.ciphertext,
      iv: row.iv,
      authTag: row.authTag,
    },
    encryptionKey,
  )
}
