-- ============================================================================
-- 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,
    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)
);

-- Ensure the future_partitions column exists for users upgrading from older versions
DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = 'partitions' AND table_name = 'config' AND column_name = 'future_partitions') THEN
        ALTER TABLE partitions.config ADD COLUMN future_partitions integer NOT NULL DEFAULT 5;
    END IF;
END $$;

-- 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
);

INSERT INTO partitions.version (version, description) VALUES ('7-2', 'Added housekeeper task interceptor trigger to drop tasks for partitioned tables')
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'),
('history_bin', 'day', '30 days')
ON CONFLICT (table_name) DO NOTHING;

-- Zabbix 8.0+ only: Uncomment the following lines if running Zabbix 8.0 or later
-- INSERT INTO partitions.config (table_name, period, keep_history) VALUES
-- ('history_json', '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;
