-- Fix: Allow users to insert their own subscription on signup
-- Run this in Supabase SQL Editor

-- Option 1: Add INSERT policy for self-signup
CREATE POLICY "user_subscriptions_insert_self" ON user_subscriptions 
FOR INSERT WITH CHECK (
  (SELECT auth.uid()) = user_id
);

-- Option 2 (better): Extend the existing handle_new_user trigger
-- This automatically creates subscription when user registers
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS trigger AS $$
BEGIN
  -- Create profile
  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;

  -- Create subscription with starter plan
  INSERT INTO public.user_subscriptions (user_id, plan_id)
  SELECT 
    new.id,
    (SELECT id FROM subscription_plans WHERE name = 'starter' LIMIT 1)
  ON CONFLICT (user_id) DO NOTHING;

  RETURN new;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
