-- 026_external_valuations.sql
-- Purpose: Unified cache for external valuation APIs — Avito IMV and Cian Valuation Calculator.
--          Replaces/supersedes avito_imv_evaluations (018) for multi-source use.
--          018 table kept for backward compat; new code writes here.
-- Dependencies:
--   - None (standalone cache table)
-- Deploy order: Apply after 025.
--
-- Sources: Schema_Cian_SERP_Inventory sec 26.3 (external_valuations DDL)
--          CianScraper_v1_Implementation_Plan Stage 1

BEGIN;

CREATE TABLE IF NOT EXISTS external_valuations (
    id              bigserial   PRIMARY KEY,
    source          text        NOT NULL,             -- 'avito_imv' / 'cian_valuation'
    cache_key       text        NOT NULL,             -- sha256(address+area+rooms+floor+repair+deal)
    -- Input snapshot
    address         text,
    total_area      numeric(8,2),
    rooms_count     int,
    floor           int,
    total_floors    int,
    repair_type     text,                             -- without/cosmetic/euro/design
    deal_type       text,                             -- sale/rent
    -- Output
    price_rub       numeric,                          -- primary estimate price
    accuracy        numeric,                          -- accuracy % (Cian-specific; 0-100)
    raw_payload     jsonb,                            -- full API response
    chart           jsonb,                            -- [{date, price}, ...] monthly points
    -- Cache TTL
    fetched_at      timestamptz NOT NULL DEFAULT NOW(),
    expires_at      timestamptz NOT NULL,             -- fetched_at + 24h typically
    UNIQUE (source, cache_key)
);

-- Cache lookup: valid entries only
CREATE INDEX IF NOT EXISTS ev_source_expires_idx
  ON external_valuations (source, expires_at DESC);

-- Address-based lookup (for analytics / dedup)
CREATE INDEX IF NOT EXISTS ev_address_idx
  ON external_valuations (address)
  WHERE address IS NOT NULL;

COMMIT;
