-- Fix the create_default_collections function to run with SECURITY DEFINER
-- This allows the trigger to bypass RLS and create collections

-- Drop the existing function
DROP FUNCTION IF EXISTS create_default_collections() CASCADE;

-- Recreate with SECURITY DEFINER
CREATE OR REPLACE FUNCTION create_default_collections()
RETURNS TRIGGER
SECURITY DEFINER -- This allows bypassing RLS
SET search_path = public
LANGUAGE plpgsql
AS $$
BEGIN
  INSERT INTO collections (user_id, name, icon) VALUES
    (NEW.id, 'Tüm Kaydedilenler', 'bookmark'),
    (NEW.id, 'Favoriler', 'heart'),
    (NEW.id, 'Görmek İstediklerim', 'eye');
  RETURN NEW;
END;
$$;

-- Recreate the trigger
DROP TRIGGER IF EXISTS on_user_created_create_collections ON profiles;
CREATE TRIGGER on_user_created_create_collections
  AFTER INSERT ON profiles
  FOR EACH ROW
  EXECUTE FUNCTION create_default_collections();

-- Grant execute permission
GRANT EXECUTE ON FUNCTION create_default_collections() TO authenticated;
GRANT EXECUTE ON FUNCTION create_default_collections() TO service_role;