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

DROP VIEW IF EXISTS partitions.monitoring;
CREATE 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
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;
