
CREATE OR REPLACE FUNCTION public.current_plan(_user_id uuid)
 RETURNS subscription_plan
 LANGUAGE plpgsql
 STABLE SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
BEGIN
  IF _user_id IS DISTINCT FROM auth.uid()
     AND NOT public.has_role(auth.uid(), 'admin') THEN
    RAISE EXCEPTION 'not authorized';
  END IF;
  RETURN COALESCE(
    (SELECT plan FROM public.subscriptions
      WHERE user_id = _user_id AND status IN ('active','trialing')
      LIMIT 1),
    'free'::public.subscription_plan
  );
END;
$function$;

REVOKE EXECUTE ON FUNCTION public.current_plan(uuid) FROM PUBLIC, anon;
GRANT EXECUTE ON FUNCTION public.current_plan(uuid) TO authenticated, service_role;
