BEGIN;

ALTER TABLE recordings
    DROP CONSTRAINT IF EXISTS chk_recordings_nonnegatives_v2;

ALTER TABLE recordings
    ADD COLUMN IF NOT EXISTS hand_day NUMERIC(15,3),
    ADD COLUMN IF NOT EXISTS hand_house NUMERIC(15,3),
    ADD COLUMN IF NOT EXISTS feed_intake NUMERIC(15,3),
    ADD COLUMN IF NOT EXISTS egg_mesh NUMERIC(15,3),
    ADD COLUMN IF NOT EXISTS egg_weight NUMERIC(15,3);

ALTER TABLE recordings
    ADD CONSTRAINT chk_recordings_nonnegatives_v3 CHECK (
        (total_depletion_qty IS NULL OR total_depletion_qty >= 0) AND
        (cum_depletion_rate  IS NULL OR cum_depletion_rate  >= 0) AND
        (daily_gain          IS NULL OR daily_gain          >= 0) AND
        (avg_daily_gain      IS NULL OR avg_daily_gain      >= 0) AND
        (cum_intake          IS NULL OR cum_intake          >= 0) AND
        (fcr_value           IS NULL OR fcr_value           >= 0) AND
        (total_chick_qty     IS NULL OR total_chick_qty     >= 0) AND
        (hand_day            IS NULL OR hand_day            >= 0) AND
        (hand_house          IS NULL OR hand_house          >= 0) AND
        (feed_intake         IS NULL OR feed_intake         >= 0) AND
        (egg_mesh            IS NULL OR egg_mesh            >= 0) AND
        (egg_weight          IS NULL OR egg_weight          >= 0)
    );

ALTER TABLE recording_eggs
    ALTER COLUMN weight TYPE NUMERIC(15,3) USING weight::NUMERIC(15,3);

ALTER TABLE recording_eggs
    DROP CONSTRAINT IF EXISTS chk_recording_eggs_qty;

ALTER TABLE recording_eggs
    ADD CONSTRAINT chk_recording_eggs_qty CHECK (
        qty >= 0 AND
        (weight IS NULL OR weight >= 0)
    );

DROP INDEX IF EXISTS idx_recording_bws_recording;
DROP TABLE IF EXISTS recording_bws;

COMMIT;
