-- 说明：为附件（media_assets）增加“可撤销删除”的软删除字段，并让自动入库队列感知删除/恢复。
-- 编码：UTF-8

alter table public.media_assets
  add column if not exists deleted_at timestamp with time zone;

alter table public.media_assets
  add column if not exists deleted_by uuid references public.profiles(id) on delete set null;

-- 说明：purged_at 表示“已过宽限期并完成清理”（删除 OCR / Storage 文件 / LightRAG 资源等）
alter table public.media_assets
  add column if not exists purged_at timestamp with time zone;

create index if not exists media_assets_deleted_at_idx
  on public.media_assets (workspace_id, deleted_at);

create index if not exists media_assets_purged_at_idx
  on public.media_assets (workspace_id, purged_at);

-- 让自动入库队列能感知 deleted_at 的变化（删除/恢复都需要入队）
drop trigger if exists enqueue_rag_for_media_asset_update on public.media_assets;
create trigger enqueue_rag_for_media_asset_update
after update on public.media_assets
for each row
when (
  old.file_url is distinct from new.file_url
  or old.storage_path is distinct from new.storage_path
  or old.bucket is distinct from new.bucket
  or old.ocr_text is distinct from new.ocr_text
  or old.ocr_status is distinct from new.ocr_status
  or old.mime_type is distinct from new.mime_type
  or old.deleted_at is distinct from new.deleted_at
  or old.purged_at is distinct from new.purged_at
)
execute function public.enqueue_rag_for_media_asset();

