-- 047_cian_history_sanitize.sql
-- Purpose: Add UNIQUE(listing_id, change_time) to offer_price_history so that
--          the `ON CONFLICT DO NOTHING` in cian_detail.save_detail_enrichment
--          is semantically correct (currently only suppresses PK conflicts).
-- Dependencies: 023_offer_price_history.sql
-- Deploy order: Apply after 046.

BEGIN;

-- Dedupe existing rows before adding constraint (safe if table empty in prod).
DELETE FROM offer_price_history a
USING offer_price_history b
WHERE a.id > b.id
  AND a.listing_id = b.listing_id
  AND a.change_time = b.change_time;

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM pg_constraint
    WHERE conname = 'offer_price_history_listing_change_uq'
  ) THEN
    ALTER TABLE offer_price_history
      ADD CONSTRAINT offer_price_history_listing_change_uq
      UNIQUE (listing_id, change_time);
  END IF;
END $$;

COMMIT;
