-- Creates a database trigger that automatically inserts default rows into
-- notification_preferences and privacy_settings whenever a new user row is
-- added. This helps ensure every account has the necessary records even if the
-- client never visits the settings page.

-- Function executed by trigger
create or replace function public.insert_default_user_settings()
returns trigger as $$
begin
  -- insert notification preferences with the same defaults used on the
  -- frontend
  insert into public.notification_preferences(
    user_id, build_likes, comments, followers, newsletter, email_updates
  ) values (
    new.user_id,
    true,  -- build_likes
    true,  -- comments
    true,  -- followers
    false, -- newsletter
    false  -- email_updates
  );

  -- insert privacy settings; table definition already has defaults but being
  -- explicit is harmless
  insert into public.privacy_settings(
    user_id, profile_public, show_builds
  ) values (
    new.user_id,
    true,  -- profile_public
    true   -- show_builds
  );

  return new;
end;
$$ language plpgsql;

-- Drop any existing trigger to avoid duplicates
drop trigger if exists trigger_insert_user_settings on public.users;

-- Create the trigger on users table
create trigger trigger_insert_user_settings
  after insert on public.users
  for each row
  execute procedure public.insert_default_user_settings();
