BEGIN;

-- Drop trigger & helper function tied to record_date before removing the column
DROP TRIGGER IF EXISTS recordings_set_record_date_trg ON recordings;
DROP FUNCTION IF EXISTS trg_set_record_date();

-- Drop indexes and constraints that reference legacy columns
DROP INDEX IF EXISTS uq_recordings_flock_record_date;
DROP INDEX IF EXISTS idx_recordings_flock_datetime;

ALTER TABLE recordings
    DROP CONSTRAINT IF EXISTS fk_recordings_project_flock,
    DROP CONSTRAINT IF EXISTS chk_recordings_status,
    DROP CONSTRAINT IF EXISTS chk_recordings_ontime,
    DROP CONSTRAINT IF EXISTS chk_recordings_nonnegatives;

-- Align recordings header with the new schema
ALTER TABLE recordings
    RENAME COLUMN project_flock_id TO project_flock_kandangs_id;

ALTER TABLE recordings
    DROP COLUMN IF EXISTS record_date,
    DROP COLUMN IF EXISTS status,
    DROP COLUMN IF EXISTS ontime,
    DROP COLUMN IF EXISTS daily_depletion_rate,
    DROP COLUMN IF EXISTS cum_depletion;

ALTER TABLE recordings
    RENAME COLUMN total_depletion TO total_depletion_qty;

ALTER TABLE recordings
    RENAME COLUMN total_chick TO total_chick_qty;

ALTER TABLE recordings
    ALTER COLUMN total_depletion_qty TYPE NUMERIC(15,3) USING COALESCE(total_depletion_qty, 0)::NUMERIC(15,3),
    ALTER COLUMN total_chick_qty TYPE NUMERIC(15,3) USING COALESCE(total_chick_qty, 0)::NUMERIC(15,3),
    ALTER COLUMN cum_intake TYPE INT USING COALESCE(cum_intake, 0)::INT;

ALTER TABLE recordings
    ADD CONSTRAINT fk_recordings_project_flock_kandang
        FOREIGN KEY (project_flock_kandangs_id) REFERENCES project_flock_kandangs(id);

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)
    );

CREATE INDEX idx_recordings_flock_datetime
    ON recordings (project_flock_kandangs_id, record_datetime);

-- recording_bws reshape
ALTER TABLE recording_bws
    RENAME COLUMN weight TO avg_weight;

ALTER TABLE recording_bws
    ALTER COLUMN avg_weight TYPE NUMERIC(8,2) USING COALESCE(avg_weight, 0)::NUMERIC(8,2);

ALTER TABLE recording_bws
    ADD COLUMN total_weight NUMERIC(10,3);

UPDATE recording_bws
SET total_weight = COALESCE(avg_weight, 0) * COALESCE(qty, 0);

ALTER TABLE recording_bws
    ALTER COLUMN total_weight SET NOT NULL;

ALTER TABLE recording_bws
    ALTER COLUMN qty TYPE NUMERIC(15,3) USING COALESCE(qty, 0)::NUMERIC(15,3);

ALTER TABLE recording_bws
    DROP COLUMN IF EXISTS notes;

ALTER TABLE recording_bws
    DROP CONSTRAINT IF EXISTS chk_recording_bws_nonneg;

ALTER TABLE recording_bws
    ADD CONSTRAINT chk_recording_bws_nonneg CHECK (
        avg_weight >= 0 AND qty >= 0 AND total_weight >= 0
    );

-- recording_depletions reshape
ALTER TABLE recording_depletions
    RENAME COLUMN total TO qty;

ALTER TABLE recording_depletions
    ALTER COLUMN qty TYPE NUMERIC(15,3) USING COALESCE(qty, 0)::NUMERIC(15,3);

ALTER TABLE recording_depletions
    DROP COLUMN IF EXISTS notes;

ALTER TABLE recording_depletions
    DROP CONSTRAINT IF EXISTS chk_recording_depl_total;

ALTER TABLE recording_depletions
    ADD CONSTRAINT chk_recording_depl_qty CHECK (qty >= 0);

-- recording_stocks reshape
ALTER TABLE recording_stocks
    DROP CONSTRAINT IF EXISTS chk_recording_stocks_nonneg;

ALTER TABLE recording_stocks
    DROP COLUMN IF EXISTS increase,
    DROP COLUMN IF EXISTS decrease,
    DROP COLUMN IF EXISTS usage_amount,
    DROP COLUMN IF EXISTS notes;

ALTER TABLE recording_stocks
    ADD COLUMN usage_qty NUMERIC(15,3),
    ADD COLUMN pending_qty NUMERIC(15,3);

ALTER TABLE recording_stocks
    ADD CONSTRAINT chk_recording_stocks_nonneg CHECK (
        (usage_qty IS NULL OR usage_qty >= 0) AND
        (pending_qty IS NULL OR pending_qty >= 0)
    );

-- recording_eggs table
CREATE TABLE recording_eggs (
    id                   BIGSERIAL PRIMARY KEY,
    recording_id         BIGINT NOT NULL,
    product_warehouse_id BIGINT NOT NULL,
    qty                  INT NOT NULL,
    created_by           BIGINT,
    created_at           TIMESTAMPTZ DEFAULT NOW(),
    updated_at           TIMESTAMPTZ DEFAULT NOW(),

    CONSTRAINT fk_recording_eggs_recording
        FOREIGN KEY (recording_id) REFERENCES recordings(id) ON DELETE CASCADE,
    CONSTRAINT fk_recording_eggs_product_warehouse
        FOREIGN KEY (product_warehouse_id) REFERENCES product_warehouses(id),
    CONSTRAINT fk_recording_eggs_created_by
        FOREIGN KEY (created_by) REFERENCES users(id),
    CONSTRAINT chk_recording_eggs_qty CHECK (qty >= 0)
);

CREATE INDEX idx_recording_eggs_recording
    ON recording_eggs (recording_id);

CREATE INDEX idx_recording_eggs_product
    ON recording_eggs (product_warehouse_id);

-- grading_eggs table
CREATE TABLE grading_eggs (
    id                BIGSERIAL PRIMARY KEY,
    recording_egg_id  BIGINT NOT NULL,
    qty               NUMERIC(15,3) NOT NULL,
    grade             VARCHAR,
    created_by        BIGINT,
    created_at        TIMESTAMPTZ DEFAULT NOW(),
    updated_at        TIMESTAMPTZ DEFAULT NOW(),

    CONSTRAINT fk_grading_eggs_recording_egg
        FOREIGN KEY (recording_egg_id) REFERENCES recording_eggs(id) ON DELETE CASCADE,
    CONSTRAINT fk_grading_eggs_created_by
        FOREIGN KEY (created_by) REFERENCES users(id),
    CONSTRAINT chk_grading_eggs_qty CHECK (qty >= 0)
);

CREATE INDEX idx_grading_eggs_recording_egg
    ON grading_eggs (recording_egg_id);

COMMIT;
