-- Competitive Intelligence & Historical Pattern Matching Layer
-- Adds tables for competitor relationships and competitive signal records.

-- ============================================================
-- Competitor Relationships
-- ============================================================

CREATE TABLE competitor_relationships (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    company_a_id UUID NOT NULL REFERENCES companies(id),
    company_b_id UUID NOT NULL REFERENCES companies(id),
    relationship_type VARCHAR(30) NOT NULL,
    strength FLOAT NOT NULL DEFAULT 0.5,
    bidirectional BOOLEAN NOT NULL DEFAULT TRUE,
    source VARCHAR(20) NOT NULL DEFAULT 'manual',
    active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT chk_relationship_type CHECK (
        relationship_type IN ('direct_rival', 'same_sector', 'overlapping_products', 'supply_chain_adjacent')
    ),
    CONSTRAINT chk_strength CHECK (strength >= 0 AND strength <= 1),
    CONSTRAINT chk_source CHECK (source IN ('manual', 'inferred')),
    CONSTRAINT chk_different_companies CHECK (company_a_id != company_b_id)
);

CREATE INDEX idx_competitor_rel_company_a ON competitor_relationships(company_a_id) WHERE active = TRUE;
CREATE INDEX idx_competitor_rel_company_b ON competitor_relationships(company_b_id) WHERE active = TRUE;
CREATE UNIQUE INDEX idx_competitor_rel_unique_pair ON competitor_relationships(
    LEAST(company_a_id, company_b_id), GREATEST(company_a_id, company_b_id)
) WHERE active = TRUE;

-- ============================================================
-- Competitive Signal Records
-- ============================================================

CREATE TABLE competitive_signal_records (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    source_document_id UUID REFERENCES documents(id),
    source_ticker VARCHAR(20) NOT NULL,
    target_ticker VARCHAR(20) NOT NULL,
    catalyst_type VARCHAR(50) NOT NULL,
    pattern_confidence FLOAT NOT NULL,
    signal_direction VARCHAR(20) NOT NULL,
    signal_strength FLOAT NOT NULL,
    relationship_strength FLOAT NOT NULL,
    computed_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_competitive_signals_target ON competitive_signal_records(target_ticker, computed_at DESC);
CREATE INDEX idx_competitive_signals_source ON competitive_signal_records(source_ticker, computed_at DESC);
