-- Bobinoo — profil allégé (28 nov. 2026). Idempotent. -- Le profil n'affiche plus les stats détaillées ni « À voir » (ils sont dans Stats et Bibliothèque), -- et « Vus récemment » montre les 5 derniers : on n'envoie plus que ça. create or replace function public.get_profile(p_username text) returns jsonb language plpgsql stable security definer set search_path = '' as $$ declare p public.profiles; me uuid := auth.uid(); res jsonb; begin if me is null then return null; end if; select * into p from public.profiles where username = lower(trim(p_username)); if not found then return null; end if; if p.suspended and p.id <> me and not public.is_admin() then return null; end if; if p.id <> me and exists (select 1 from public.blocks b where b.blocker_id = p.id and b.blocked_id = me) then return null; end if; res := public.profile_card(p) || jsonb_build_object( 'bio', p.bio, 'banner_url', p.banner_url, 'is_me', p.id = me, 'follows_me', exists (select 1 from public.follows where follower_id = p.id and following_id = me and status = 'accepted'), 'followers', (select count(*) from public.follows where following_id = p.id and status = 'accepted'), 'following', (select count(*) from public.follows where follower_id = p.id and status = 'accepted'), 'visible', public.can_view(p.id) ); if public.can_view(p.id) then res := res || jsonb_build_object( 'stats', jsonb_build_object( 'finished', (select count(*) from public.items where user_id = p.id and not deleted and data->>'status' = 'termine') ), 'top', ( select coalesce(jsonb_agg(public.public_item(data) order by data->'top'->>'category', (data->'top'->>'rank')), '[]'::jsonb) from public.items i where i.user_id = p.id and not i.deleted and jsonb_typeof(i.data->'top') = 'object' and coalesce( (select s.data->'topCategories' ? (i.data->'top'->>'category') from public.settings s where s.user_id = p.id and jsonb_typeof(s.data->'topCategories') = 'array'), true) ), 'recent', ( select coalesce(jsonb_agg(public.public_item(s.data) order by s.k desc nulls last), '[]'::jsonb) from ( select data, coalesce(data->>'endDate', data->>'startDate') as k from public.items where user_id = p.id and not deleted and data->>'status' = 'termine' order by k desc nulls last limit 5 ) s ), 'watching', ( select coalesce(jsonb_agg(public.public_item(s.data) order by s.k desc nulls last), '[]'::jsonb) from ( select data, coalesce(data->>'startDate', left(data->>'updatedAt', 10)) as k from public.items where user_id = p.id and not deleted and data->>'status' = 'en_cours' order by k desc nulls last limit 8 ) s ) ); end if; return res; end; $$; revoke execute on function public.get_profile(text) from public, anon; grant execute on function public.get_profile(text) to authenticated;