-- Console : nommer ou retirer un admin (30/11/2026). Idempotent. -- Garde-fous : double authentification active exigée, pas de compte suspendu, jamais sur son propre compte -- (il reste donc toujours au moins un admin). Inscrit au journal. create or replace function admin.set_admin(p_admin uuid, p_user uuid, p_value boolean, p_reason text) returns jsonb language plpgsql set search_path = '' as $$ begin if p_user = p_admin then raise exception 'impossible sur son propre compte'; end if; if p_value then if not exists (select 1 from auth.mfa_factors f where f.user_id = p_user and f.status = 'verified') then raise exception 'double authentification requise'; end if; if exists (select 1 from public.profiles p where p.id = p_user and p.suspended) then raise exception 'compte suspendu'; end if; insert into admin.admins (user_id) values (p_user) on conflict do nothing; else delete from admin.admins where user_id = p_user; end if; if not found then return jsonb_build_object('ok', false); end if; perform admin.log(p_admin, case when p_value then 'nommer admin' else 'retirer admin' end, p_user, (select username from public.profiles where id = p_user), jsonb_build_object('motif', left(p_reason, 500))); return jsonb_build_object('ok', true); end; $$; revoke all on function admin.set_admin(uuid, uuid, boolean, text) from public, anon, authenticated, service_role; comment on function admin.set_admin(uuid, uuid, boolean, text) is 'Nommer ou retirer un admin (double authentification exigée, jamais sur son propre compte). Inscrit au journal.';