-- 006_core_deal.sql — core.deal + core.deal_team_member (Битрикс CAT=16)

CREATE TABLE core.deal (
    id bigserial PRIMARY KEY,
    bitrix_id bigint UNIQUE NOT NULL,
    title text,
    category_id int,
    stage_id text,
    stage_semantic_id char(1),
    opportunity decimal(15,2),
    begindate date,
    closedate date,
    assigned_to_id bigint REFERENCES core.employee,
    bitrix_company_id bigint,
    bitrix_company_name text,
    project_manager_id bigint REFERENCES core.employee,
    is_in_forecast boolean DEFAULT false,
    last_synced timestamptz
);

CREATE INDEX idx_deal_stage ON core.deal (stage_id);
CREATE INDEX idx_deal_forecast ON core.deal (is_in_forecast) WHERE is_in_forecast = true;
CREATE INDEX idx_deal_category ON core.deal (category_id);

CREATE TABLE core.deal_team_member (
    deal_id bigint REFERENCES core.deal ON DELETE CASCADE,
    employee_id bigint REFERENCES core.employee,
    weight decimal(5,2) NOT NULL DEFAULT 1.0,
    is_manual_override boolean DEFAULT false,
    PRIMARY KEY (deal_id, employee_id)
);

CREATE INDEX idx_deal_team_employee ON core.deal_team_member (employee_id);
