-- Create tags table with hierarchical support
CREATE TABLE IF NOT EXISTS tags
(
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    name        TEXT      NOT NULL UNIQUE,
    category    TEXT      NOT NULL,           -- 'geographic', 'content', 'source', 'custom'
    description TEXT,
    color       TEXT,                         -- Hex color for UI display
    usage_count INTEGER   NOT NULL DEFAULT 0,
    parent_id   INTEGER REFERENCES tags (id), -- For hierarchical tags (e.g., Country -> Region -> City)
    created_at  TIMESTAMP NOT NULL DEFAULT (datetime('now'))
);

-- Create article_tags junction table
CREATE TABLE IF NOT EXISTS article_tags
(
    article_id       INTEGER   NOT NULL REFERENCES articles (id) ON DELETE CASCADE,
    tag_id           INTEGER   NOT NULL REFERENCES tags (id) ON DELETE CASCADE,
    confidence_score REAL               DEFAULT 1.0, -- AI confidence (0.0-1.0)
    ai_generated     BOOLEAN   NOT NULL DEFAULT 0,
    created_at       TIMESTAMP NOT NULL DEFAULT (datetime('now')),
    PRIMARY KEY (article_id, tag_id)
);

-- Create indexes
CREATE INDEX IF NOT EXISTS idx_tags_category ON tags (category);
CREATE INDEX IF NOT EXISTS idx_tags_parent_id ON tags (parent_id);
CREATE INDEX IF NOT EXISTS idx_tags_usage_count ON tags (usage_count DESC);
CREATE INDEX IF NOT EXISTS idx_article_tags_article_id ON article_tags (article_id);
CREATE INDEX IF NOT EXISTS idx_article_tags_tag_id ON article_tags (tag_id);
CREATE INDEX IF NOT EXISTS idx_article_tags_ai_generated ON article_tags (ai_generated);
