-- 044_external_valuations_link.sql
-- Purpose: Link external_valuations to canonical entities (house/listing) + add
--          sale band columns (low/high) per Cross_Source_Matching sec 13.1.
--          Table base in 026 + 029. Existing UNIQUE (source, cache_key) preserved.
-- Dependencies: 026_external_valuations.sql, 029_extend_matching_valuation_dynamics.sql,
--               009_houses.sql, 002_core_tables.sql (listings)

BEGIN;

ALTER TABLE external_valuations
  ADD COLUMN IF NOT EXISTS house_id   bigint REFERENCES houses(id)   ON DELETE CASCADE,
  ADD COLUMN IF NOT EXISTS listing_id bigint REFERENCES listings(id) ON DELETE CASCADE,
  ADD COLUMN IF NOT EXISTS low_price  bigint,
  ADD COLUMN IF NOT EXISTS high_price bigint;

CREATE INDEX IF NOT EXISTS external_valuations_house_idx
  ON external_valuations (house_id)
  WHERE house_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS external_valuations_listing_idx
  ON external_valuations (listing_id)
  WHERE listing_id IS NOT NULL;

CREATE UNIQUE INDEX IF NOT EXISTS external_valuations_canonical_uniq_idx
  ON external_valuations (source, house_id, listing_id)
  WHERE house_id IS NOT NULL AND listing_id IS NOT NULL;

COMMENT ON COLUMN external_valuations.house_id IS
  'FK to canonical house (post-matching). NULL for pre-matching cache rows keyed by cache_key.';
COMMENT ON COLUMN external_valuations.listing_id IS
  'FK to canonical listing (post-matching). NULL for house-level estimates.';
COMMENT ON COLUMN external_valuations.low_price IS
  'Lower bound of sale band (Cian sometimes returns; NULL for Avito IMV).';
COMMENT ON COLUMN external_valuations.high_price IS
  'Upper bound of sale band.';

COMMIT;
