-- Create a materialized view for efficient tag searching
-- This aggregates all tags from active posts and their counts
-- Used by the search Edge Function to avoid downloading all posts

CREATE OR REPLACE VIEW view_searchable_tags AS
SELECT
  unnest(tags) as tag,
  COUNT(*) as count
FROM posts
WHERE
  deleted_at IS NULL
  AND tags IS NOT NULL
  AND array_length(tags, 1) > 0
GROUP BY unnest(tags)
ORDER BY count DESC;

-- Create an index on the view for faster tag searches
-- Note: We can't create indexes on regular views, but we document this for potential future materialized view
-- If performance becomes an issue with large datasets, convert this to a MATERIALIZED VIEW and add:
-- CREATE INDEX idx_searchable_tags_tag ON view_searchable_tags(tag);
-- Then add a refresh strategy (e.g., REFRESH MATERIALIZED VIEW view_searchable_tags CONCURRENTLY)
