-- 022_agents_table.sql
-- Purpose: Create agents table for Cian seller/agent profiles; link to listings.
-- Dependencies:
--   - listings table (002_core_tables.sql / 011_listings_alter.sql)
-- Deploy order: Apply after 021.
--
-- Sources: Schema_Cian_SERP_Inventory sec 20.3 (offerData.agent structure)

BEGIN;

CREATE TABLE IF NOT EXISTS agents (
    id              bigserial   PRIMARY KEY,
    ext_source      text        NOT NULL,             -- 'cian' / 'avito'
    ext_agent_id    text        NOT NULL,             -- Cian cianUserId (as text for flexibility)
    company_name    text,                             -- 'Новосёл' (агентство)
    is_pro          boolean,                          -- PRO подписка
    skills          jsonb,                            -- [{id, name, parentName}, ...]
    account_type    text,                             -- specialist/agent/agency
    created_at      timestamptz NOT NULL DEFAULT NOW(),
    UNIQUE (ext_source, ext_agent_id)
);

CREATE INDEX IF NOT EXISTS agents_source_ext_idx
  ON agents (ext_source, ext_agent_id);

CREATE INDEX IF NOT EXISTS agents_company_idx
  ON agents (company_name)
  WHERE company_name IS NOT NULL;

-- Link listings to agent profiles
ALTER TABLE listings
  ADD COLUMN IF NOT EXISTS agent_id_fk bigint REFERENCES agents(id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS listings_agent_idx
  ON listings (agent_id_fk)
  WHERE agent_id_fk IS NOT NULL;

COMMIT;
