-- Fix for user registration trigger
-- Run this in Supabase SQL Editor

-- Simplified trigger - only creates profile, no subscription insert
-- (subscription is handled client-side after signup)
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS trigger AS $$
BEGIN
  -- Create profile only
  INSERT INTO public.profiles (id, username, avatar_url)
  VALUES (
    new.id, 
    COALESCE(new.raw_user_meta_data->>'username', 'user_' || substr(new.id::text, 1, 8)), 
    new.raw_user_meta_data->>'avatar_url'
  )
  ON CONFLICT (id) DO NOTHING;

  RETURN new;
EXCEPTION WHEN OTHERS THEN
  -- Log but don't fail user creation
  RAISE WARNING 'handle_new_user failed: %', SQLERRM;
  RETURN new;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- Allow users to insert their own subscription
CREATE POLICY "user_subscriptions_insert_self" ON user_subscriptions 
FOR INSERT WITH CHECK (
  (SELECT auth.uid()) = user_id
);
