-- 003__staging.sql
-- Staging-схема. Структура повторяет fansy.*, плюс loaded_at и
-- допущения на промежуточные NULL'ы (валидация будет в процессе
-- перелива в fansy.*).

SET search_path TO fansy_staging, public;

CREATE TABLE IF NOT EXISTS participants (
    inn                          varchar(10) PRIMARY KEY,
    ogrn                         varchar(15),
    full_name_rus                text,
    short_name_rus               text,
    display_name_rus             text,
    full_name_eng                text,
    short_name_eng               text,
    display_name_eng             text,
    depository_participant_code  varchar(12),
    broker_participant_code      varchar(12),
    is_available_for_m2m         boolean,
    comment                      text,
    loaded_at                    timestamptz NOT NULL DEFAULT now()
);
COMMENT ON TABLE participants IS 'Staging для справочника участников. Перезаливка целиком, не чаще раза в сутки.';

CREATE TABLE IF NOT EXISTS securities (
    security_code     char(12) PRIMARY KEY,
    isin              char(12),
    classification    varchar(4),
    category          varchar(4),
    security_type     varchar(256),
    security_series   text,
    reg_number        varchar(256),
    fund_class        varchar(120),
    display_name      text,
    loaded_at         timestamptz NOT NULL DEFAULT now()
);
COMMENT ON TABLE securities IS 'Staging для справочника ЦБ. Перезаливка целиком.';

CREATE TABLE IF NOT EXISTS clients (
    id           uuid PRIMARY KEY,
    inn          varchar(12),
    last_name    varchar(50),
    first_name   varchar(50),
    middle_name  varchar(50),
    birth_date   date,
    loaded_at    timestamptz NOT NULL DEFAULT now()
);
COMMENT ON TABLE clients IS 'Staging для клиентов. Инкрементный UPSERT по id.';

CREATE TABLE IF NOT EXISTS client_documents (
    id             uuid PRIMARY KEY,
    client_id      uuid NOT NULL,
    document_type  varchar(2),
    series         text,
    number         text,
    issued_at      date,
    issuer         text,
    loaded_at      timestamptz NOT NULL DEFAULT now()
);
COMMENT ON TABLE client_documents IS 'Staging для документов клиента. UPSERT по id.';

CREATE TABLE IF NOT EXISTS iia_contracts (
    id                uuid PRIMARY KEY,
    client_id         uuid NOT NULL,
    agreement_type    varchar(3),
    agreement_number  varchar(128),
    agreement_date    date,
    broker_inn        varchar(10),
    loaded_at         timestamptz NOT NULL DEFAULT now()
);
COMMENT ON TABLE iia_contracts IS 'Staging для договоров ИИС.';

CREATE TABLE IF NOT EXISTS settlement_requisites (
    id            uuid PRIMARY KEY,
    inn           varchar(10) NOT NULL,
    display_name  text,
    loaded_at     timestamptz NOT NULL DEFAULT now()
);
COMMENT ON TABLE settlement_requisites IS 'Staging для реквизитов расчётов.';

CREATE TABLE IF NOT EXISTS depo_accounts (
    id              uuid PRIMARY KEY,
    client_id       uuid NOT NULL,
    deponent_code   varchar(50),
    account_id      varchar(50),
    section_id      varchar(50),
    depository_inn  varchar(10),
    is_active       boolean,
    is_trading      boolean,
    loaded_at       timestamptz NOT NULL DEFAULT now()
);
COMMENT ON TABLE depo_accounts IS 'Staging для депо-счетов.';

CREATE TABLE IF NOT EXISTS portfolios (
    id                    uuid PRIMARY KEY,
    client_id             uuid NOT NULL,
    depo_account_id       uuid NOT NULL,
    security_code         char(12) NOT NULL,
    isin                  char(12),
    quantity_whole        numeric(38, 0),
    quantity_fractional   numeric(38, 16),
    isolation_status      varchar(4),
    valued_at             timestamptz,
    loaded_at             timestamptz NOT NULL DEFAULT now()
);
COMMENT ON TABLE portfolios IS 'Staging для портфелей. UPSERT по id; SLA свежести — 1 мин.';

CREATE INDEX IF NOT EXISTS idx_stg_portfolios_loaded ON portfolios(loaded_at DESC);
CREATE INDEX IF NOT EXISTS idx_stg_clients_loaded ON clients(loaded_at DESC);
