-- Deploy schemas/rag/procedures/drop_vector_index to pg
-- made with <3 @ constructive.io

-- requires: rag-core

BEGIN;

CREATE FUNCTION rag.drop_vector_index(
  p_index_name text
) RETURNS boolean
LANGUAGE plpgsql
AS $$
BEGIN
  EXECUTE format('DROP INDEX IF EXISTS rag.%I', p_index_name);
  RETURN true;
EXCEPTION
  WHEN OTHERS THEN
    RETURN false;
END;
$$;

COMMENT ON FUNCTION rag.drop_vector_index(text) IS 'Drop a vector index by name';

CREATE FUNCTION rag.list_vector_indexes(
  p_collection_id uuid DEFAULT NULL
) RETURNS TABLE (
  index_name text,
  index_type text,
  index_size text
)
LANGUAGE plpgsql
STABLE
AS $$
BEGIN
  RETURN QUERY
  SELECT 
    i.indexname::text AS index_name,
    am.amname::text AS index_type,
    pg_size_pretty(pg_relation_size(c.oid)) AS index_size
  FROM pg_indexes i
  JOIN pg_class c ON c.relname = i.indexname AND c.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = i.schemaname)
  JOIN pg_am am ON am.oid = c.relam
  WHERE i.schemaname = 'rag'
    AND i.tablename = 'embedding'
    AND am.amname IN ('hnsw', 'ivfflat')
    AND (p_collection_id IS NULL OR i.indexname LIKE '%' || replace(p_collection_id::text, '-', '_') || '%');
END;
$$;

COMMENT ON FUNCTION rag.list_vector_indexes(uuid) IS 'List vector indexes, optionally filtered by collection';

COMMIT;
