-- ============================================================================
-- SCRIPT: 00_partitions_init.sql
-- DESCRIPTION: Creates the 'partitions' schema and configuration table.
--              Defines the structure for managing Zabbix partitioning.
-- ============================================================================

CREATE SCHEMA IF NOT EXISTS partitions;

-- Configuration table to store partitioning settings per table
CREATE TABLE IF NOT EXISTS partitions.config (
    table_name      text NOT NULL,
    period          text NOT NULL CHECK (period IN ('day', 'week', 'month', 'year')),
    keep_history    interval NOT NULL,
    future_partitions integer NOT NULL DEFAULT 5,
    last_updated    timestamp WITH TIME ZONE DEFAULT (now() AT TIME ZONE 'UTC'),
    PRIMARY KEY (table_name)
);

-- Table to track installed version of the partitioning solution
CREATE TABLE IF NOT EXISTS partitions.version (
    version text PRIMARY KEY,
    installed_at timestamp with time zone DEFAULT (now() AT TIME ZONE 'UTC'),
    description text
);

-- Set initial version
INSERT INTO partitions.version (version, description) VALUES ('1.0', 'Initial release')
ON CONFLICT (version) DO NOTHING;

-- Default configuration for Zabbix tables (adjust as needed)
-- History tables: Daily partitions, keep 30 days
INSERT INTO partitions.config (table_name, period, keep_history) VALUES
('history', 'day', '30 days'),
('history_uint', 'day', '30 days'),
('history_str', 'day', '30 days'),
('history_log', 'day', '30 days'),
('history_text', 'day', '30 days')
ON CONFLICT (table_name) DO NOTHING;

-- Trends tables: Monthly partitions, keep 12 months
INSERT INTO partitions.config (table_name, period, keep_history) VALUES
('trends', 'month', '12 months'),
('trends_uint', 'month', '12 months')
ON CONFLICT (table_name) DO NOTHING;

-- Auditlog: Monthly partitions, keep 12 months
INSERT INTO partitions.config (table_name, period, keep_history) VALUES
('auditlog', 'month', '12 months')
ON CONFLICT (table_name) DO NOTHING;
