BEGIN;

ALTER TABLE daily_checklists
    DROP CONSTRAINT IF EXISTS fk_daily_checklists_kandang;

UPDATE daily_checklists dc
SET kandang_id = k.id
FROM kandangs k
WHERE
    dc.kandang_id = k.kandang_group_id;

ALTER TABLE daily_checklists
    ADD CONSTRAINT fk_daily_checklists_kandang
        FOREIGN KEY (kandang_id) REFERENCES kandangs (id) ON DELETE CASCADE;

DROP INDEX IF EXISTS idx_kandangs_kandang_group_id;

ALTER TABLE kandangs
    DROP CONSTRAINT IF EXISTS fk_kandangs_kandang_group;

ALTER TABLE kandangs
    DROP COLUMN IF EXISTS kandang_group_id;

DROP INDEX IF EXISTS kandang_groups_name_unique;

DROP TABLE IF EXISTS kandang_groups;

COMMIT;
