-- Fix the handle_new_user function to use existing organization if provided
CREATE OR REPLACE FUNCTION public.handle_new_user()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public', 'auth'
AS $function$
DECLARE
  organization_id UUID;
BEGIN
  -- Check if organization_id is provided in metadata
  IF NEW.raw_user_meta_data->>'organization_id' IS NOT NULL THEN
    -- Use the existing organization
    organization_id := (NEW.raw_user_meta_data->>'organization_id')::UUID;
  ELSE
    -- Create new organization if none provided
    INSERT INTO public.organizations (
      name,
      subscription_tier,
      subscription_status
    ) VALUES (
      COALESCE(NEW.raw_user_meta_data->>'organization_name', NEW.raw_user_meta_data->>'name' || '''s Organization'),
      'free',
      'active'
    )
    RETURNING id INTO organization_id;
  END IF;

  -- Create the user profile
  INSERT INTO public.users (
    id,
    email,
    name,
    organization_id,
    role,
    is_active,
    settings,
    created_at,
    updated_at
  ) VALUES (
    NEW.id,
    NEW.email,
    COALESCE(NEW.raw_user_meta_data->>'name', split_part(NEW.email, '@', 1)),
    organization_id,
    COALESCE(NEW.raw_user_meta_data->>'role', 'owner')::user_role,
    true,
    jsonb_build_object(
      'email_notifications', true,
      'notification_frequency', 'instant',
      'dashboard_layout', 'default'
    ),
    NOW(),
    NOW()
  );

  RETURN NEW;
EXCEPTION
  WHEN others THEN
    -- Log the error (will appear in Postgres logs)
    RAISE LOG 'Error in handle_new_user: %', SQLERRM;
    RETURN NEW;
END;
$function$;

-- Refresh schema cache
NOTIFY pgrst, 'reload schema';
