BEGIN;

DO $$
BEGIN
    IF to_regclass('public.fifo_stock_v2_overconsume_rules') IS NOT NULL THEN
        EXECUTE '
            DELETE FROM fifo_stock_v2_overconsume_rules
            WHERE reason IN (
                ''fifo_v2_default_allow'',
                ''fifo_v2_exception_ayam_depletion_block'',
                ''fifo_v2_exception_marketing_block'',
                ''fifo_v2_exception_transfer_block'',
                ''fifo_v2_exception_adjustment_block'',
                ''fifo_v2_exception_transfer_laying_block''
            )
        ';
    END IF;

    IF to_regclass('public.fifo_stock_v2_route_rules') IS NOT NULL THEN
        EXECUTE '
            DELETE FROM fifo_stock_v2_route_rules
            WHERE flag_group_code IN (''AYAM'', ''AFKIR_CULLING_MATI'', ''PAKAN'', ''OVK'', ''TELUR'', ''TELUR_GRADE'')
        ';
    END IF;

    IF to_regclass('public.fifo_stock_v2_traits') IS NOT NULL THEN
        EXECUTE '
            DELETE FROM fifo_stock_v2_traits
            WHERE source_table IN (
                ''purchase_items'',
                ''stock_transfer_details'',
                ''laying_transfer_targets'',
                ''laying_transfer_sources'',
                ''adjustment_stocks'',
                ''recording_stocks'',
                ''recording_depletions'',
                ''recording_eggs'',
                ''marketing_delivery_products'',
                ''project_chickins'',
                ''project_flock_populations''
            )
        ';
    END IF;

    IF to_regclass('public.fifo_stock_v2_flag_members') IS NOT NULL THEN
        EXECUTE '
            DELETE FROM fifo_stock_v2_flag_members
            WHERE flag_group_code IN (''AYAM'', ''AFKIR_CULLING_MATI'', ''PAKAN'', ''OVK'', ''TELUR'', ''TELUR_GRADE'')
        ';
    END IF;

    IF to_regclass('public.fifo_stock_v2_flag_groups') IS NOT NULL THEN
        EXECUTE '
            DELETE FROM fifo_stock_v2_flag_groups
            WHERE code IN (''AYAM'', ''AFKIR_CULLING_MATI'', ''PAKAN'', ''OVK'', ''TELUR'', ''TELUR_GRADE'')
        ';
    END IF;
END $$;

COMMIT;
