-- 说明：为“删除文件时清理 LightRAG 资源”补齐删除触发器，避免垃圾堆积。
-- 编码：UTF-8

-- media_assets：硬删除时也要入队（让 ingest_service 删除 LightRAG doc）
create or replace function public.enqueue_rag_for_media_asset_delete()
returns trigger
language plpgsql
as $function$
declare
  v_user_id uuid;
begin
  select user_id
    into v_user_id
    from public.documents
   where id = old.document_id;

  perform public.upsert_rag_index_source(
    old.workspace_id,
    'media_asset',
    old.id,
    old.document_id,
    coalesce(old.created_by, v_user_id),
    timezone('utc', now())
  );
  return old;
end;
$function$;

drop trigger if exists enqueue_rag_for_media_asset_delete on public.media_assets;
create trigger enqueue_rag_for_media_asset_delete
after delete on public.media_assets
for each row execute function public.enqueue_rag_for_media_asset_delete();

-- mindmap_nodes：硬删除节点时，也入队（让 ingest_service 删除/重建 mindmap 对应索引）
create or replace function public.enqueue_rag_for_mindmap_node_delete()
returns trigger
language plpgsql
as $function$
declare
  v_user_id uuid;
begin
  select user_id
    into v_user_id
    from public.documents
   where id = old.document_id;

  perform public.upsert_rag_index_source(
    old.workspace_id,
    'mindmap',
    old.mindmap_id,
    old.document_id,
    v_user_id,
    timezone('utc', now())
  );
  return old;
end;
$function$;

drop trigger if exists enqueue_rag_for_mindmap_node_delete on public.mindmap_nodes;
create trigger enqueue_rag_for_mindmap_node_delete
after delete on public.mindmap_nodes
for each row execute function public.enqueue_rag_for_mindmap_node_delete();

