-- 105_add_sales_started_flag.sql
--
-- Context: SF FixList #18 (Wave 3)
-- Purpose: Expose is_sales_started flag on domrf_kn_objects so SiteFinder can
--          distinguish "Строящиеся с открытыми продажами" from pre-sale buildings
--          (those where domrf_kn_flats has no rows for that obj_id yet).
--
-- Design decision: VIEW instead of GENERATED ALWAYS AS column.
--   - PostgreSQL GENERATED columns do not support subqueries (only immutable expressions).
--   - A VIEW is idempotent (CREATE OR REPLACE), needs no backfill, and stays fresh.
--   - Consumers query v_domrf_objects_with_sales in place of domrf_kn_objects where
--     the flag is needed; the base table remains unchanged for scrapers / ON CONFLICT.
--
-- Audit (2026-05-17, region_cd=66, site_status='Строящиеся'):
--   total_buildings: 1322
--   with_flats (is_sales_started=TRUE):  1247  (94.3%)
--   without_flats (pre-sale / no flats):   75  ( 5.7%)
--
-- Dependencies: domrf_kn_objects, domrf_kn_flats
-- Deploy order: standalone, no existing deps to drop first
-- Idempotent: yes (CREATE OR REPLACE VIEW)

BEGIN;

CREATE OR REPLACE VIEW v_domrf_objects_with_sales AS
SELECT
    o.*,
    EXISTS (
        SELECT 1
        FROM domrf_kn_flats f
        WHERE f.obj_id = o.obj_id
    ) AS is_sales_started
FROM domrf_kn_objects o;

COMMENT ON VIEW v_domrf_objects_with_sales IS
    'domrf_kn_objects + is_sales_started (bool). '
    'TRUE когда в domrf_kn_flats есть хотя бы одна запись для данного obj_id. '
    'Позволяет отличать строящиеся дома с открытыми продажами от pre-sale объектов.';

COMMENT ON COLUMN v_domrf_objects_with_sales.is_sales_started IS
    'Derived: TRUE если EXISTS (SELECT 1 FROM domrf_kn_flats WHERE obj_id = o.obj_id). '
    'Pre-sale = FALSE (квартиры ещё не выложены на domrf.ru).';

COMMIT;
