-- 021_management_companies.sql
-- Purpose: Create management_companies table for ТСЖ/УК data from Cian Valuation Calculator.
--          Also adds FK constraint to houses.management_company_id (column added in 020).
-- Dependencies:
--   - 020_houses_alter_cian.sql must be applied first (adds management_company_id column to houses)
-- Deploy order: Apply after 020.
--
-- Sources: Schema_Cian_SERP_Inventory sec 26.3

BEGIN;

CREATE TABLE IF NOT EXISTS management_companies (
    id              bigserial PRIMARY KEY,
    name            text        NOT NULL,             -- 'ТСЖ "УЧИТЕЛЕЙ, 18"'
    phones          text[],                           -- array of phone strings
    email           text,
    opening_hours   text,                             -- raw string or serialised schedule
    chief_name      text,                             -- ФИО руководителя
    ext_source      text        NOT NULL DEFAULT 'cian',
    ext_id          bigint,                           -- Cian's internal management company ID if available
    created_at      timestamptz NOT NULL DEFAULT NOW(),
    UNIQUE (ext_source, name, ext_id)
);

-- ext_source + ext_id for dedup when Cian provides numeric ID
CREATE INDEX IF NOT EXISTS mc_ext_source_id_idx
  ON management_companies (ext_source, ext_id)
  WHERE ext_id IS NOT NULL;

-- Text search on company name
CREATE INDEX IF NOT EXISTS mc_name_idx
  ON management_companies (name);

-- Add FK from houses.management_company_id to this table
-- Column management_company_id was added in 020_houses_alter_cian.sql as plain bigint
ALTER TABLE houses
  DROP CONSTRAINT IF EXISTS houses_management_company_id_fkey;

ALTER TABLE houses
  ADD CONSTRAINT houses_management_company_id_fkey
  FOREIGN KEY (management_company_id)
  REFERENCES management_companies (id)
  ON DELETE SET NULL;

COMMIT;
