-- ============================================================================
-- SCRIPT: 03_enable_partitioning.sql
-- DESCRIPTION: Converts standard Zabbix tables to Partitioned tables.
--              WARNING: This renames existing tables to *_old.
-- ============================================================================

DO $$
DECLARE
    v_row record;
    v_table text;
    v_old_table text;
    v_pk_sql text;
BEGIN
    FOR v_row IN SELECT * FROM partitions.config LOOP
        v_table := v_row.table_name;
        v_old_table := v_table || '_old';
        
        -- Check if table exists and is NOT already partitioned
        IF EXISTS (SELECT 1 FROM pg_class WHERE relname = v_table AND relkind = 'r') THEN
            RAISE NOTICE 'Converting table % to partitioned table...', v_table;
            
            -- 1. Rename existing table
            EXECUTE format('ALTER TABLE public.%I RENAME TO %I', v_table, v_old_table);
            
            -- 2. Create new partitioned table (copying structure)
            EXECUTE format('CREATE TABLE public.%I (LIKE public.%I INCLUDING ALL) PARTITION BY RANGE (clock)', v_table, v_old_table);
            
            -- 3. Create initial partitions
            RAISE NOTICE 'Creating initial partitions for %...', v_table;
            CALL partitions.maintain_table(v_table, v_row.period, v_row.keep_history, v_row.future_partitions); 
            
            -- Optional: Migrate existing data
            -- EXECUTE format('INSERT INTO public.%I SELECT * FROM public.%I', v_table, v_old_table);
            
        ELSIF EXISTS (SELECT 1 FROM pg_class WHERE relname = v_table AND relkind = 'p') THEN
             RAISE NOTICE 'Table % is already partitioned. Skipping conversion.', v_table;
             -- Just run maintenance to ensure partitions exist
             CALL partitions.run_maintenance();
        ELSE
             RAISE WARNING 'Table % not found!', v_table;
        END IF;
    END LOOP;
END $$;
