-- 023_offer_price_history.sql
-- Purpose: Per-listing price change history from Cian offerData.priceChanges
--          (and optionally Avito equivalent when available).
-- Dependencies:
--   - listings table (002_core_tables.sql)
-- Deploy order: Apply after 022.
--
-- Sources: Schema_Cian_SERP_Inventory sec 16.2, 20.2 (priceChanges array)

BEGIN;

CREATE TABLE IF NOT EXISTS offer_price_history (
    id              bigserial   PRIMARY KEY,
    listing_id      bigint      NOT NULL REFERENCES listings(id) ON DELETE CASCADE,
    change_time     timestamptz NOT NULL,             -- changeTime from Cian (ISO-8601)
    price_rub       numeric     NOT NULL,             -- priceData.price в рублях
    diff_percent    numeric(5,2),                     -- вычисленный % относительно предыдущей точки
    source          text,                             -- 'cian' / 'avito'
    recorded_at     timestamptz NOT NULL DEFAULT NOW()
);

-- Primary access pattern: get ordered history for a listing
CREATE INDEX IF NOT EXISTS oph_listing_time_idx
  ON offer_price_history (listing_id, change_time DESC);

-- Source-level stats
CREATE INDEX IF NOT EXISTS oph_source_time_idx
  ON offer_price_history (source, change_time DESC);

COMMIT;
