-- Migration: Create norda_knowledge_chunks table
-- Date: 2026-01-28
-- Description: Knowledge base for Norda GPT from forum and chat

-- Create knowledge chunks table
CREATE TABLE IF NOT EXISTS norda_knowledge_chunks (
    id SERIAL PRIMARY KEY,

    -- Content
    content TEXT NOT NULL,
    summary VARCHAR(500),

    -- Source tracking
    source_type VARCHAR(50) NOT NULL,  -- forum_topic, forum_reply, chat_response, manual
    source_id INTEGER,  -- ID in source table
    source_url VARCHAR(500),

    -- Metadata
    category VARCHAR(100),
    keywords TEXT,  -- Comma-separated keywords

    -- Development insights (for roadmap)
    insight_category VARCHAR(50),  -- feature_request, bug_report, improvement, question, pain_point, etc.
    insight_priority INTEGER DEFAULT 0,  -- Higher = more important (based on frequency)
    insight_status VARCHAR(50) DEFAULT 'new',  -- new, reviewed, planned, implemented, rejected

    -- Quality indicators
    is_verified BOOLEAN DEFAULT FALSE,
    confidence_score INTEGER DEFAULT 50,  -- 0-100

    -- Companies mentioned (comma-separated IDs)
    mentioned_company_ids TEXT,

    -- Timestamps
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW(),
    source_created_at TIMESTAMP,

    -- Status
    is_active BOOLEAN DEFAULT TRUE
);

-- Indexes for efficient queries
CREATE INDEX IF NOT EXISTS idx_norda_knowledge_source_type ON norda_knowledge_chunks(source_type);
CREATE INDEX IF NOT EXISTS idx_norda_knowledge_source_id ON norda_knowledge_chunks(source_type, source_id);
CREATE INDEX IF NOT EXISTS idx_norda_knowledge_active ON norda_knowledge_chunks(is_active);
CREATE INDEX IF NOT EXISTS idx_norda_knowledge_category ON norda_knowledge_chunks(category);
CREATE INDEX IF NOT EXISTS idx_norda_knowledge_created ON norda_knowledge_chunks(created_at DESC);

-- Full-text search index (PostgreSQL)
CREATE INDEX IF NOT EXISTS idx_norda_knowledge_content_fts
ON norda_knowledge_chunks USING gin(to_tsvector('polish', content));

-- Development insights indexes
CREATE INDEX IF NOT EXISTS idx_norda_knowledge_insight_cat ON norda_knowledge_chunks(insight_category);
CREATE INDEX IF NOT EXISTS idx_norda_knowledge_insight_status ON norda_knowledge_chunks(insight_status);
CREATE INDEX IF NOT EXISTS idx_norda_knowledge_insight_priority ON norda_knowledge_chunks(insight_priority DESC);

-- Comments
COMMENT ON TABLE norda_knowledge_chunks IS 'Knowledge base for Norda GPT - facts from forum and chat';
COMMENT ON COLUMN norda_knowledge_chunks.source_type IS 'Source: forum_topic, forum_reply, chat_response, manual';
COMMENT ON COLUMN norda_knowledge_chunks.confidence_score IS 'Quality score 0-100, higher = more reliable';

-- Grant permissions
GRANT SELECT, INSERT, UPDATE, DELETE ON norda_knowledge_chunks TO nordabiz_app;
GRANT USAGE, SELECT ON SEQUENCE norda_knowledge_chunks_id_seq TO nordabiz_app;
