create or replace function kit.setup_new_user()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
declare
    user_name text;
    picture_url text;
    personal_code text;
begin
    if new.raw_user_meta_data ->> 'name' is not null then
        user_name := new.raw_user_meta_data ->> 'name';
    end if;

    if user_name is null and new.email is not null then
        user_name := split_part(new.email, '@', 1);
    end if;

    if user_name is null then
        user_name := '';
    end if;

    if new.raw_user_meta_data ->> 'avatar_url' is not null then
        picture_url := new.raw_user_meta_data ->> 'avatar_url';
    else
        picture_url := null;
    end if;

    personal_code := new.raw_user_meta_data ->> 'personalCode';

    insert into public.accounts (
        id,
        primary_owner_user_id,
        name,
        is_personal_account,
        picture_url,
        email,
        personal_code
    )
    values (
        new.id,
        new.id,
        user_name,
        true,
        picture_url,
        new.email,
        personal_code
    );

    return new;
end;
$$;
