-- 124_cad_buildings_local.sql
-- Local materialized mirror of gendesign_cad_buildings (postgres_fdw foreign table)
-- for fast geo-nearest building matching of listings.
--
-- WHY (perf fact, measured live):
--   gendesign_cad_buildings is a postgres_fdw foreign table (~36.7k EKB rows) with NO
--   PostGIS geom — only scalar lat/lon. A per-listing nearest-building query over the FDW
--   takes ~1.16s/row (lat/lon bbox prefilter). With ~43k listings that is ~13h — UNUSABLE.
--   Solution: materialize the FDW once into a LOCAL table with a real Point geom + GIST
--   index, then run a fast local KNN nearest-neighbour join (geom <-> point, GIST-backed).
--
-- This migration creates the EMPTY table + indexes only. It does NOT read the FDW —
--   so deploy never depends on the gendesign DB / FDW server being reachable.
--   The table is populated by the refresh job (app/tasks/refresh_cad_buildings_local.py),
--   driven by the in-app scheduler (source='cadastral_geo_match', combined refresh+match).
--
-- Schedule seed (cadastral_geo_match) lives in 125_scrape_schedules_seed_cadastral_geo_match.sql.
--
-- DEPENDENCIES: PostGIS (postgis extension, present since geom on listings/houses).
-- Idempotent: CREATE TABLE/INDEX IF NOT EXISTS. Safe to re-run.

BEGIN;

CREATE TABLE IF NOT EXISTS cad_buildings_local (
    cad_num          text PRIMARY KEY,
    readable_address text,
    year_built       int,
    floors           int,
    area_m2          numeric,
    purpose          text,
    lat              double precision,
    lon              double precision,
    geom             geometry(Point, 4326)
);

COMMENT ON TABLE cad_buildings_local IS
    'Local mirror of gendesign_cad_buildings FDW (Rosreestr building registry, EKB ~36.7k). '
    'Populated by app/tasks/refresh_cad_buildings_local.py (single bulk FDW scan, TRUNCATE+INSERT). '
    'Point geom + GIST enables fast local KNN nearest-building matching '
    '(run_cadastral_geo_match) for listings.building_cadastral_number. '
    'Migration 124. Refresh+match driven by scheduler source=cadastral_geo_match.';

-- GIST on geom — required for the KNN <-> operator and ST_DWithin predicate.
CREATE INDEX IF NOT EXISTS cad_buildings_local_geom_idx
    ON cad_buildings_local USING GIST (geom);

COMMIT;
