BEGIN;

DO $$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM daily_checklists
        WHERE category::text = 'empty_kandang'
    ) THEN
        RAISE EXCEPTION 'Cannot rollback category_code enum: daily_checklists still contains empty_kandang';
    END IF;

    IF EXISTS (
        SELECT 1
        FROM phases
        WHERE category::text = 'empty_kandang'
    ) THEN
        RAISE EXCEPTION 'Cannot rollback category_code enum: phases still contains empty_kandang';
    END IF;
END $$;

ALTER TYPE category_code RENAME TO category_code_old;

CREATE TYPE category_code AS ENUM (
    'pullet_open',
    'pullet_close',
    'produksi_open',
    'produksi_close'
);

ALTER TABLE phases
    ALTER COLUMN category TYPE category_code
    USING category::text::category_code;

ALTER TABLE daily_checklists
    ALTER COLUMN category TYPE category_code
    USING category::text::category_code;

DROP TYPE category_code_old;

COMMIT;
