create or replace function public.handle_user_login(
  user_email text,
  user_full_name text,
  user_avatar_url text
)
returns void
language plpgsql
security definer
as $$
declare
  current_user_id uuid;
begin
  current_user_id := auth.uid();
  if current_user_id is null then
    raise exception 'Not authenticated';
  end if;

  insert into public.users (id, email, full_name, avatar_url, credits)
  values (
    current_user_id,
    user_email,
    user_full_name,
    user_avatar_url,
    5
  )
  on conflict (id) do update set
    email = excluded.email,
    full_name = excluded.full_name,
    avatar_url = excluded.avatar_url;
end;
$$;

grant execute on function public.handle_user_login to authenticated;
