-- Dynamic Credit Initialization Migration
-- Run this in Supabase SQL Editor

-- Updated trigger: Creates profile, subscription, AND credits dynamically
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS trigger AS $$
DECLARE
    starter_plan_id UUID;
    plan_credits INTEGER;
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;

    -- Get starter plan ID and credits
    SELECT id, monthly_credits INTO starter_plan_id, plan_credits
    FROM subscription_plans 
    WHERE name = 'starter' 
    LIMIT 1;

    -- Create subscription with starter plan
    IF starter_plan_id IS NOT NULL THEN
        INSERT INTO public.user_subscriptions (user_id, plan_id)
        VALUES (new.id, starter_plan_id)
        ON CONFLICT (user_id) DO NOTHING;
    END IF;

    -- Create user_credits with plan's monthly_credits
    INSERT INTO public.user_credits (user_id, balance, total_purchased, total_used)
    VALUES (new.id, COALESCE(plan_credits, 10), 0, 0)
    ON CONFLICT (user_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 SET search_path = '';

-- RLS Policy for user_subscriptions insert (for client-side fallback)
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_policies 
        WHERE schemaname = 'public' 
        AND tablename = 'user_subscriptions' 
        AND policyname = 'user_subscriptions_insert_self'
    ) THEN
        CREATE POLICY "user_subscriptions_insert_self" ON user_subscriptions 
        FOR INSERT WITH CHECK ((SELECT auth.uid()) = user_id);
    END IF;
END $$;

-- RLS Policy for user_credits insert (for lazy initialization fallback)
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_policies 
        WHERE schemaname = 'public' 
        AND tablename = 'user_credits' 
        AND policyname = 'user_credits_insert_self'
    ) THEN
        CREATE POLICY "user_credits_insert_self" ON user_credits 
        FOR INSERT WITH CHECK ((SELECT auth.uid()) = user_id);
    END IF;
END $$;
