-- Fix auto_create_entity_version function to handle system updates without user context
CREATE OR REPLACE FUNCTION public.auto_create_entity_version()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
DECLARE
  v_entity_type TEXT;
  v_change_type version_change_type;
  v_user_id UUID;
  v_version_data JSONB;
BEGIN
  -- Determine entity type from table name
  v_entity_type := CASE TG_TABLE_NAME
    WHEN 'parks' THEN 'park'
    WHEN 'rides' THEN 'ride'
    WHEN 'companies' THEN 'company'
    WHEN 'ride_models' THEN 'ride_model'
    WHEN 'photos' THEN 'photo'
    ELSE substring(TG_TABLE_NAME from 1 for length(TG_TABLE_NAME) - 1)
  END;

  -- Determine change type
  v_change_type := CASE TG_OP
    WHEN 'INSERT' THEN 'created'::version_change_type
    WHEN 'UPDATE' THEN 'updated'::version_change_type
    ELSE 'updated'::version_change_type
  END;

  -- Get user from session or auth context
  BEGIN
    v_user_id := current_setting('app.current_user_id', true)::UUID;
  EXCEPTION WHEN OTHERS THEN
    v_user_id := auth.uid();
  END;

  -- Convert NEW record to JSONB
  v_version_data := to_jsonb(NEW);

  -- Only create version if we have a user context
  -- Skip versioning for system migrations/updates
  IF v_user_id IS NOT NULL THEN
    PERFORM public.create_entity_version(
      v_entity_type,
      NEW.id,
      v_version_data,
      v_user_id,
      CASE TG_OP
        WHEN 'INSERT' THEN 'Entity created'
        WHEN 'UPDATE' THEN 'Entity updated'
        ELSE 'Entity modified'
      END,
      NULL,
      v_change_type
    );
  END IF;

  RETURN NEW;
END;
$function$;