-- Atomic collection creation + owner membership insert
-- Run this in Supabase SQL Editor.

create or replace function public.create_collection_with_owner(
  p_name text,
  p_description text default null
)
returns public.collections
language plpgsql
security definer
set search_path = public
as $$
declare
  v_user_id uuid := auth.uid();
  v_collection public.collections;
begin
  if v_user_id is null then
    raise exception 'Not authenticated';
  end if;

  insert into public.collections (
    name,
    owner_id,
    description
  )
  values (
    p_name,
    v_user_id,
    nullif(trim(p_description), '')
  )
  returning * into v_collection;

  insert into public.collection_members (
    collection_id,
    user_id,
    role
  )
  values (
    v_collection.id,
    v_user_id,
    'owner'
  );

  return v_collection;
end;
$$;

grant execute on function public.create_collection_with_owner(text, text) to authenticated;
