BEGIN;

ALTER TABLE recording_stocks
    ADD COLUMN IF NOT EXISTS project_flock_kandang_id BIGINT NULL;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'fk_recording_stocks_project_flock_kandang_id'
    ) THEN
        ALTER TABLE recording_stocks
            ADD CONSTRAINT fk_recording_stocks_project_flock_kandang_id
            FOREIGN KEY (project_flock_kandang_id)
            REFERENCES project_flock_kandangs(id)
            ON DELETE SET NULL
            ON UPDATE CASCADE;
    END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_recording_stocks_project_flock_kandang_id
    ON recording_stocks(project_flock_kandang_id);

ALTER TABLE house_depreciation_standards
    ADD COLUMN IF NOT EXISTS standard_week INT;

UPDATE house_depreciation_standards
SET standard_week = CASE house_type::text
    WHEN 'close_house' THEN 22
    WHEN 'open_house' THEN 25
    ELSE standard_week
END
WHERE standard_week IS NULL OR standard_week <= 0;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'chk_house_depreciation_standards_standard_week_positive'
    ) THEN
        ALTER TABLE house_depreciation_standards
            ADD CONSTRAINT chk_house_depreciation_standards_standard_week_positive
            CHECK (standard_week > 0);
    END IF;
END $$;

ALTER TABLE house_depreciation_standards
    ALTER COLUMN standard_week SET NOT NULL;

COMMIT;
