import { getSupabaseClient } from '../../../../supabase/server/client'
import { setKek, CURRENT_KEY_ID } from './encryption'

let loaded = false

/**
 * Loads the platform credential KEK from Supabase Vault and registers it under
 * `CURRENT_KEY_ID` ('platform-v1').
 *
 * Idempotent: subsequent calls are no-ops.
 *
 * Fails fast on missing / malformed Vault KEK so misconfigured deploys do not
 * silently start without a usable encryption key.
 */
export async function loadCredentialKEKs(): Promise<void> {
  if (loaded) return

  const supabase = await getSupabaseClient()
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- RPC isn't in generated types yet (run `supabase gen types` post-merge)
  const { data, error } = await (supabase.rpc as any)('get_platform_credential_kek')
  if (error) {
    throw new Error(
      `Failed to load platform credential KEK from Vault: ${error.message}. ` +
        `Did you run provision-credential-kek.sql against this environment?`
    )
  }
  if (typeof data !== 'string' || data.length === 0) {
    throw new Error('Vault returned null/empty platform credential KEK')
  }
  const vaultKek = Buffer.from(data, 'hex')
  if (vaultKek.length !== 32) {
    throw new Error(`Vault KEK is ${vaultKek.length} bytes, expected 32`)
  }
  setKek(CURRENT_KEY_ID, vaultKek)

  loaded = true
}
