-- database/scripts/health_check.sql

\echo '================================================================='
\echo 'PostgreSQL Health Check'
\echo '================================================================='

-- Database size
\echo '\nDatabase Sizes:'
SELECT 
  datname as database,
  pg_size_pretty(pg_database_size(datname)) as size
FROM pg_database
WHERE datname LIKE 'aurganize%'
ORDER BY pg_database_size(datname) DESC;

-- Table sizes
\echo '\nTop 10 Largest Tables:'
SELECT 
  schemaname,
  tablename,
  pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) as size
FROM pg_tables
WHERE schemaname = 'public'
ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC
LIMIT 10;

-- Active connections
\echo '\nActive Connections:'
SELECT 
  count(*) as connections,
  state
FROM pg_stat_activity
WHERE datname LIKE 'aurganize%'
GROUP BY state;

-- Slow queries (if any)
\echo '\nSlow Queries (> 1 second):'
SELECT 
  pid,
  now() - query_start as duration,
  state,
  substring(query, 1, 60) as query
FROM pg_stat_activity
WHERE state = 'active'
  AND now() - query_start > interval '1 second'
ORDER BY duration DESC;

-- Cache hit ratio (should be > 99%)
\echo '\nCache Hit Ratio:'
SELECT 
  sum(heap_blks_hit) / (sum(heap_blks_hit) + sum(heap_blks_read)) * 100 
  as cache_hit_ratio
FROM pg_statio_user_tables;

-- Index usage
\echo '\nUnused Indexes:'
SELECT 
  schemaname,
  tablename,
  indexname,
  idx_scan as index_scans
FROM pg_stat_user_indexes
WHERE idx_scan = 0
  AND indexname NOT LIKE '%_pkey'
ORDER BY pg_relation_size(indexrelid) DESC
LIMIT 10;

\echo '\n================================================================='
\echo 'Health Check Complete'
\echo '================================================================='