-- 033_listings_alter_yandex.sql
-- Purpose: Add Yandex Realty-specific columns to listings table (SERP + detail fields).
-- Dependencies: listings table created in 002_core_tables.sql / 011_listings_alter.sql
--               019_listings_alter_cian.sql already adds views_total (int) for Cian.
--               Yandex gets a parallel column views_total_yandex to preserve source attribution —
--               a single shared column cannot distinguish which scraper wrote the value when both
--               are active concurrently (conflict-resolution ambiguity).
-- Deploy order: Apply after 029_extend_matching_valuation_dynamics.sql
--
-- Sources:
--   - decisions/Schema_YandexRealty_Recon.md sec 10.1 (SERP offer card)
--   - decisions/Schema_YandexRealty_Recon.md sec 12.3 (OfferCardAuthorInfo agency block)
--   - YandexRealtyScraper_v1_Implementation_Plan Stage 1
--
-- Idempotent: all ALTER TABLE uses ADD COLUMN IF NOT EXISTS; all CREATE INDEX use IF NOT EXISTS.

BEGIN;

ALTER TABLE listings
  -- Yandex Realty offer identification
  ADD COLUMN IF NOT EXISTS yandex_offer_id            text,         -- numeric string (e.g. '7567094292504417257'), kept as text

  -- Yandex SERP/detail stats
  ADD COLUMN IF NOT EXISTS views_total_yandex         int,          -- "N просмотров" из OfferCardSummary; views_total already used by Cian
  ADD COLUMN IF NOT EXISTS publish_date_relative      text,         -- "6 часов назад" / "вчера" / "N дней назад" raw text

  -- Yandex sale type (text form differs from Cian sale_type enum)
  ADD COLUMN IF NOT EXISTS sale_type_text             text,         -- 'свободная продажа' / 'альтернативная' (raw RU phrase)

  -- Yandex agency block (OfferCardAuthorInfo)
  ADD COLUMN IF NOT EXISTS agency_name                text,         -- 'Агентство «Диал»'
  ADD COLUMN IF NOT EXISTS agency_founded_year        int,          -- "Год основания N" parsed
  ADD COLUMN IF NOT EXISTS agency_objects_count       int;          -- "N объектов" parsed

-- Partial index on yandex_offer_id for fast lookup by Yandex identifier
CREATE INDEX IF NOT EXISTS listings_yandex_offer_id_idx
  ON listings (yandex_offer_id)
  WHERE yandex_offer_id IS NOT NULL;

-- Partial index on agency_name for analytics queries filtered by agency
CREATE INDEX IF NOT EXISTS listings_agency_name_idx
  ON listings (agency_name)
  WHERE agency_name IS NOT NULL;

COMMIT;
