-- Create trigger on profiles table to auto-assign admin role for admin@demo.com
DROP TRIGGER IF EXISTS on_demo_admin_profile_created ON public.profiles;

CREATE TRIGGER on_demo_admin_profile_created
  AFTER INSERT ON public.profiles
  FOR EACH ROW
  EXECUTE FUNCTION public.handle_demo_admin_role();

-- Also create a policy to allow the first admin to be created (bootstrap)
-- This allows inserting a role when no admin exists yet
CREATE OR REPLACE FUNCTION public.no_admin_exists()
RETURNS boolean
LANGUAGE sql
STABLE
SECURITY DEFINER
SET search_path = public
AS $$
  SELECT NOT EXISTS (
    SELECT 1 FROM public.user_roles WHERE role = 'admin'
  )
$$;

-- Allow first admin setup when no admin exists
CREATE POLICY "Allow first admin setup"
ON public.user_roles
FOR INSERT
WITH CHECK (
  public.no_admin_exists() AND role = 'admin' AND auth.uid() = user_id
);