BEGIN;

CREATE TABLE IF NOT EXISTS recording_bws (
    id            BIGSERIAL PRIMARY KEY,
    recording_id  BIGINT NOT NULL,
    avg_weight    NUMERIC(8,2) NOT NULL,
    qty           NUMERIC(15,3) NOT NULL DEFAULT 1,
    total_weight  NUMERIC(10,3) NOT NULL,
    created_at    TIMESTAMPTZ DEFAULT NOW(),
    updated_at    TIMESTAMPTZ DEFAULT NOW(),

    CONSTRAINT fk_recording_bws_recording
        FOREIGN KEY (recording_id) REFERENCES recordings(id) ON DELETE CASCADE,

    CONSTRAINT chk_recording_bws_nonneg
        CHECK (avg_weight >= 0 AND qty >= 0 AND total_weight >= 0)
);

CREATE INDEX IF NOT EXISTS idx_recording_bws_recording
    ON recording_bws (recording_id);

ALTER TABLE recordings
    DROP CONSTRAINT IF EXISTS chk_recordings_nonnegatives_v3;

ALTER TABLE recordings
    DROP COLUMN IF EXISTS hand_day,
    DROP COLUMN IF EXISTS hand_house,
    DROP COLUMN IF EXISTS feed_intake,
    DROP COLUMN IF EXISTS egg_mesh,
    DROP COLUMN IF EXISTS egg_weight;

ALTER TABLE recordings
    ADD CONSTRAINT chk_recordings_nonnegatives_v2 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)
    );

ALTER TABLE recording_eggs
    DROP CONSTRAINT IF EXISTS chk_recording_eggs_qty;

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

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

COMMIT;
