-- ============================================================
-- 桃育种业务流完善·既有表补列（2026-08-05）——幂等
-- 背景：create_all 只建新表不补已有表列；以下 4 处均对既有表 ADD COLUMN IF NOT EXISTS。
--   A1 采收结构化：bre_field_operation 补产量构成四列（op_type=harvest）
--   A3 种质级观测：bre_observation 补 germplasm_id（描述性观测目标）
--   A4 关联补链：  bre_seed_lot 补 pollination_id / bre_seed_treatment 补 seed_lot_id
-- ============================================================

-- A1 采收产量构成 ------------------------------------------------
ALTER TABLE bre_field_operation ADD COLUMN IF NOT EXISTS yield_kg double precision;
ALTER TABLE bre_field_operation ADD COLUMN IF NOT EXISTS fruit_count integer;
ALTER TABLE bre_field_operation ADD COLUMN IF NOT EXISTS avg_fruit_weight double precision;
ALTER TABLE bre_field_operation ADD COLUMN IF NOT EXISTS marketable_rate double precision;
COMMENT ON COLUMN bre_field_operation.yield_kg IS '单株产量(kg，op_type=harvest)';
COMMENT ON COLUMN bre_field_operation.fruit_count IS '果实个数(op_type=harvest)';
COMMENT ON COLUMN bre_field_operation.avg_fruit_weight IS '平均单果重(g，op_type=harvest)';
COMMENT ON COLUMN bre_field_operation.marketable_rate IS '好果率(%，op_type=harvest)';

-- A3 种质级观测 --------------------------------------------------
ALTER TABLE bre_observation ADD COLUMN IF NOT EXISTS germplasm_id integer;
DO $$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'bre_observation_germplasm_id_fkey') THEN
    ALTER TABLE bre_observation ADD CONSTRAINT bre_observation_germplasm_id_fkey
      FOREIGN KEY (germplasm_id) REFERENCES bre_germplasm(id) ON DELETE CASCADE;
  END IF;
END $$;
CREATE INDEX IF NOT EXISTS ix_bre_observation_germplasm_id ON bre_observation (germplasm_id);
COMMENT ON COLUMN bre_observation.germplasm_id IS '种质资源(可空，描述性观测)';

-- A4 授粉→收种关联 ----------------------------------------------
ALTER TABLE bre_seed_lot ADD COLUMN IF NOT EXISTS pollination_id integer;
DO $$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'bre_seed_lot_pollination_id_fkey') THEN
    ALTER TABLE bre_seed_lot ADD CONSTRAINT bre_seed_lot_pollination_id_fkey
      FOREIGN KEY (pollination_id) REFERENCES bre_pollination(id) ON DELETE SET NULL;
  END IF;
END $$;
CREATE INDEX IF NOT EXISTS ix_bre_seed_lot_pollination_id ON bre_seed_lot (pollination_id);
COMMENT ON COLUMN bre_seed_lot.pollination_id IS '授粉记录(关联补链)';

-- A4 收种→种子处理关联 -------------------------------------------
ALTER TABLE bre_seed_treatment ADD COLUMN IF NOT EXISTS seed_lot_id integer;
DO $$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'bre_seed_treatment_seed_lot_id_fkey') THEN
    ALTER TABLE bre_seed_treatment ADD CONSTRAINT bre_seed_treatment_seed_lot_id_fkey
      FOREIGN KEY (seed_lot_id) REFERENCES bre_seed_lot(id) ON DELETE SET NULL;
  END IF;
END $$;
CREATE INDEX IF NOT EXISTS ix_bre_seed_treatment_seed_lot_id ON bre_seed_treatment (seed_lot_id);
COMMENT ON COLUMN bre_seed_treatment.seed_lot_id IS '种子批(关联补链)';
