BEGIN;

ALTER TABLE recordings
    DROP CONSTRAINT IF EXISTS chk_recordings_nonnegatives_v4;

DO $$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_name = 'recordings' AND column_name = 'hen_day'
    ) THEN
        ALTER TABLE recordings RENAME COLUMN hen_day TO hand_day;
    END IF;
END $$;

DO $$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_name = 'recordings' AND column_name = 'hen_house'
    ) THEN
        ALTER TABLE recordings RENAME COLUMN hen_house TO hand_house;
    END IF;
END $$;

DO $$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_name = 'recordings' AND column_name = 'egg_mass'
    ) THEN
        ALTER TABLE recordings RENAME COLUMN egg_mass TO egg_mesh;
    END IF;
END $$;

ALTER TABLE recordings
    ADD COLUMN IF NOT EXISTS daily_gain NUMERIC(7,3),
    ADD COLUMN IF NOT EXISTS avg_daily_gain NUMERIC(7,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)
    );

COMMIT;
