-- ============================================================================
-- Creates a view to monitor partition status and sizes.
-- ============================================================================

CREATE OR REPLACE VIEW partitions.monitoring AS
SELECT
    parent.relname AS parent_table,
    c.table_name,
    c.period,
    c.keep_history,
    c.future_partitions AS configured_future_partitions,
    count(child.relname) AS partition_count,
    count(child.relname) FILTER (
        WHERE
           (c.period = 'day' AND child.relname > (parent.relname || '_p' || to_char(now() AT TIME ZONE 'UTC', 'YYYYMMDD')))
           OR
           (c.period = 'month' AND child.relname > (parent.relname || '_p' || to_char(now() AT TIME ZONE 'UTC', 'YYYYMM')))
           OR
           (c.period = 'week' AND child.relname > (parent.relname || '_p' || to_char(date_trunc('week', now() AT TIME ZONE 'UTC'), 'YYYYMMDD')))
           OR
           (c.period LIKE '%hour%' AND child.relname > (parent.relname || '_p' || to_char(now() AT TIME ZONE 'UTC', 'YYYYMMDDHH24')))
    ) AS actual_future_partitions,
    sum(pg_total_relation_size(child.oid)) AS total_size_bytes,
    pg_size_pretty(sum(pg_total_relation_size(child.oid))) AS total_size,
    min(child.relname) AS oldest_partition,
    max(child.relname) AS newest_partition,
    c.last_updated
FROM partitions.config c
JOIN pg_class parent ON parent.relname = c.table_name AND pg_table_is_visible(parent.oid)
LEFT JOIN pg_inherits ON pg_inherits.inhparent = parent.oid
LEFT JOIN pg_class child ON pg_inherits.inhrelid = child.oid
WHERE parent.relkind = 'p' -- Only partitioned tables
GROUP BY parent.relname, c.table_name, c.period, c.keep_history, c.future_partitions, c.last_updated;

-- ============================================================================
-- IMPORTANT: Since DROP VIEW / CREATE VIEW resets permissions, we automatically
-- grant read access to PUBLIC. This ensures that whatever monitoring user
-- (e.g. zbx_monitor) is connecting to the DB will always be able to read 
-- the monitoring stats without manual intervention after upgrades.
-- ==========================================================================
GRANT USAGE ON SCHEMA partitions TO PUBLIC;
GRANT SELECT ON partitions.monitoring TO PUBLIC;
