
-- Add default system settings for credits
INSERT INTO public.system_settings (key, value, category, description)
VALUES 
  ('credits_per_build', '1', 'builds', 'Number of credits consumed per app build'),
  ('default_signup_credits', '5', 'app', 'Number of free credits given to new users on signup')
ON CONFLICT (key) DO NOTHING;

-- Update the trigger function to read default credits from system_settings
CREATE OR REPLACE FUNCTION public.handle_new_user_credits()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
DECLARE
  free_plan_id UUID;
  default_credits INTEGER;
BEGIN
  -- Get default signup credits from system settings (fallback to 5)
  SELECT COALESCE((value::text)::integer, 5) INTO default_credits
  FROM public.system_settings
  WHERE key = 'default_signup_credits'
  LIMIT 1;

  IF default_credits IS NULL THEN
    default_credits := 5;
  END IF;

  -- Get the free plan ID
  SELECT id INTO free_plan_id FROM public.subscription_plans WHERE tier = 'free' LIMIT 1;
  
  -- Create user credits record with admin-configured default credits
  INSERT INTO public.user_credits (user_id, monthly_credits, bonus_credits, credits_reset_at)
  VALUES (NEW.id, default_credits, 0, now() + interval '1 month')
  ON CONFLICT (user_id) DO NOTHING;
  
  -- Create default free subscription if not exists
  IF free_plan_id IS NOT NULL THEN
    INSERT INTO public.user_subscriptions (user_id, plan_id, current_period_end)
    VALUES (NEW.id, free_plan_id, now() + interval '1 month')
    ON CONFLICT (user_id) DO NOTHING;
  END IF;
  
  RETURN NEW;
END;
$function$;
