-- Fix collaboration bootstrap RLS flow:
-- 1) Allow authenticated users to create organizations they own.
-- 2) Allow org owner to insert their initial owner membership row.

drop policy if exists "organizations_insert_owner" on public.organizations;
create policy "organizations_insert_owner"
  on public.organizations
  for insert
  to authenticated
  with check (
    owner_user_id = auth.uid()
    and owner_user_id is not null
  );

drop policy if exists "organization_members_insert_admins" on public.organization_members;
create policy "organization_members_insert_admins"
  on public.organization_members
  for insert
  to authenticated
  with check (
    user_id = auth.uid()
    and (
      public.org_role(organization_id) in ('owner', 'admin')
      or exists (
        select 1
        from public.organizations o
        where o.id = organization_id
          and o.owner_user_id = auth.uid()
      )
    )
  );
