-- ============================================================================
-- EduAdvise CRM — Fix: B2B partners must NOT inherit branch-wide lead visibility.
-- A partner is assigned a branch so they can CREATE leads, but the leads SELECT
-- policy's "branch_id in my branches" clause then exposed every lead in that
-- branch to them. Partners are external sub-agents — they may see only leads
-- they created (or are explicitly assigned). Gate the branch clause to non-
-- partners. (Found by tests/rls.test.mjs.)
-- ============================================================================

create or replace function public.is_b2b_partner()
returns boolean
language sql stable security definer set search_path = public
as $$
  select exists (
    select 1 from public.users u
    join public.roles r on r.id = u.role_id
    where u.id = auth.uid() and r.slug = 'b2b-partner'
  );
$$;

drop policy if exists "read leads" on public.leads;
create policy "read leads" on public.leads
  for select to authenticated
  using (
    public.is_super_admin()
    or (
      branch_id in (select public.current_user_branch_ids())
      and not public.is_b2b_partner()
    )
    or created_by = auth.uid()
    or id in (select public.current_user_assigned_lead_ids())
  );
