BEGIN;

CREATE TABLE IF NOT EXISTS trade_in_estimates (
    id              uuid PRIMARY KEY DEFAULT gen_random_uuid(),

    -- Input snapshot
    address         text NOT NULL,
    lat             double precision,
    lon             double precision,
    area_m2         numeric(8, 2) NOT NULL,
    rooms           int NOT NULL,
    floor           int NOT NULL,
    total_floors    int NOT NULL,
    year_built      int,
    house_type      text,
    repair_state    text,
    has_balcony     boolean,

    -- Output
    median_price        bigint NOT NULL,
    range_low           bigint NOT NULL,
    range_high          bigint NOT NULL,
    median_price_per_m2 int NOT NULL,
    confidence          text NOT NULL CHECK (confidence IN ('low', 'medium', 'high')),
    n_analogs           int NOT NULL DEFAULT 0,
    analogs             jsonb NOT NULL DEFAULT '[]'::jsonb,
    actual_deals        jsonb NOT NULL DEFAULT '[]'::jsonb,

    -- Metadata
    created_at  timestamptz NOT NULL DEFAULT NOW(),
    expires_at  timestamptz NOT NULL DEFAULT NOW() + interval '24 hours'
);

CREATE INDEX IF NOT EXISTS trade_in_estimates_created_idx
    ON trade_in_estimates (created_at DESC);

CREATE INDEX IF NOT EXISTS trade_in_estimates_expires_idx
    ON trade_in_estimates (expires_at);

COMMENT ON TABLE trade_in_estimates IS
    '#314 TradeIn MVP — стор estimates с input snapshot + aggregated output. TTL 24h.';

COMMIT;
