-- Create trigger function to auto-assign admin role to demo admin account
CREATE OR REPLACE FUNCTION public.handle_demo_admin_role()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
  -- Auto-assign admin role to admin@demo.com
  IF NEW.email = 'admin@demo.com' THEN
    INSERT INTO public.user_roles (user_id, role)
    VALUES (NEW.id, 'admin')
    ON CONFLICT (user_id, role) DO NOTHING;
  END IF;
  
  RETURN NEW;
END;
$$;

-- Create trigger that fires after a profile is created
DROP TRIGGER IF EXISTS on_profile_created_assign_demo_role ON public.profiles;
CREATE TRIGGER on_profile_created_assign_demo_role
  AFTER INSERT ON public.profiles
  FOR EACH ROW
  EXECUTE FUNCTION public.handle_demo_admin_role();