-- Database Performance Optimization: Additional Indexes
-- Focus: Speed up frequently queried fields

-- Products: Add missing indexes for common queries
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_products_slug ON products(slug) WHERE isactive = true;
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_products_active_featured ON products(isactive, isfeatured) WHERE isactive = true AND isfeatured = true;
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_products_active_category ON products(isactive, category) WHERE isactive = true;

-- Blog: Add slug index for single post queries
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_blogposts_slug ON blogposts(slug) WHERE ispublished = true;
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_blogposts_published ON blogposts(ispublished, createdat DESC) WHERE ispublished = true;

-- Portfolio: Add composite index for common query patterns
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_portfolio_active_display ON portfolioprojects(isactive, displayorder, createdat DESC) WHERE isactive = true;

-- Analyze tables to update statistics for query planner
ANALYZE products;
ANALYZE product_images;
ANALYZE blogposts;
ANALYZE portfolioprojects;
ANALYZE pages;

-- Add database-level connection pooling settings for better performance
ALTER DATABASE skyartshop SET random_page_cost = 1.1; -- SSD optimization
ALTER DATABASE skyartshop SET effective_cache_size = '2GB'; -- Assume 2GB available for caching
ALTER DATABASE skyartshop SET shared_buffers = '512MB'; -- Increase shared buffer
ALTER DATABASE skyartshop SET work_mem = '16MB'; -- Increase work memory for sorting
ALTER DATABASE skyartshop SET maintenance_work_mem = '128MB'; -- For VACUUM and CREATE INDEX

-- Vacuum analyze to reclaim space and update statistics
VACUUM ANALYZE;
