-- ============================================================
-- Vault helper functions
-- Migration: 002_vault_helpers.sql
-- These wrap vault.create_secret / vault.update_secret 
-- so Edge Functions don't need direct vault schema access
-- ============================================================

-- Upsert a secret (create or update)
create or replace function public.vault_upsert_secret(
  secret_name text,
  secret_value text
)
returns void
language plpgsql
security definer
as $$
declare
  existing_id uuid;
begin
  select id into existing_id
  from vault.secrets
  where name = secret_name
  limit 1;

  if existing_id is not null then
    perform vault.update_secret(existing_id, secret_value);
  else
    perform vault.create_secret(secret_value, secret_name);
  end if;
end;
$$;

-- Decrypt and return a secret value by name
create or replace function public.vault_decrypt_secret(
  secret_name text
)
returns text
language plpgsql
security definer
as $$
declare
  result text;
begin
  select decrypted_secret into result
  from vault.decrypted_secrets
  where name = secret_name
  limit 1;
  return result;
end;
$$;

-- Delete a secret by name
create or replace function public.vault_delete_secret(
  secret_name text
)
returns void
language plpgsql
security definer
as $$
declare
  target_id uuid;
begin
  select id into target_id
  from vault.secrets
  where name = secret_name
  limit 1;

  if target_id is not null then
    delete from vault.secrets where id = target_id;
  end if;
end;
$$;

-- List all clauth secrets (names only — never values)
create or replace function public.vault_list_clauth_secrets()
returns table(name text, created_at timestamptz, updated_at timestamptz)
language sql
security definer
as $$
  select name, created_at, updated_at
  from vault.secrets
  where name like 'clauth.%'
  order by name;
$$;

-- Revoke execute from public, grant to service_role only
revoke execute on function public.vault_upsert_secret from public;
revoke execute on function public.vault_decrypt_secret from public;
revoke execute on function public.vault_delete_secret from public;
revoke execute on function public.vault_list_clauth_secrets from public;
