-- Social Analytics Tables
-- Task #108: TikTok Analytics Dashboard (Phase 1 - Manual Entry)
-- Created by Chronicler #76

-- Platform enum for future expansion
CREATE TYPE social_platform AS ENUM ('tiktok', 'facebook', 'instagram', 'x', 'bluesky');

-- Individual post tracking
CREATE TABLE social_posts (
    id SERIAL PRIMARY KEY,
    platform social_platform NOT NULL DEFAULT 'tiktok',
    post_title VARCHAR(255) NOT NULL,
    post_url VARCHAR(500),
    posted_at TIMESTAMP NOT NULL,
    video_length_seconds INTEGER,
    
    -- Core engagement metrics
    views INTEGER DEFAULT 0,
    likes INTEGER DEFAULT 0,
    comments INTEGER DEFAULT 0,
    shares INTEGER DEFAULT 0,
    saves INTEGER DEFAULT 0,
    
    -- Watch metrics
    total_play_time_seconds INTEGER DEFAULT 0,
    avg_watch_time_seconds DECIMAL(10,2) DEFAULT 0,
    watched_full_pct DECIMAL(5,2) DEFAULT 0,
    drop_off_seconds INTEGER,
    
    -- Growth metrics
    new_followers INTEGER DEFAULT 0,
    
    -- Traffic source (store top source)
    top_traffic_source VARCHAR(50),
    top_traffic_pct DECIMAL(5,2),
    
    -- Metadata
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW(),
    notes TEXT,
    
    -- Platform native ID (for Phase 2 API matching)
    platform_post_id VARCHAR(255)
);

-- Account-level snapshots (weekly or on-demand)
CREATE TABLE social_account_snapshots (
    id SERIAL PRIMARY KEY,
    platform social_platform NOT NULL DEFAULT 'tiktok',
    snapshot_date DATE NOT NULL,
    
    -- Account metrics
    total_followers INTEGER DEFAULT 0,
    profile_views INTEGER DEFAULT 0,
    
    -- Top search queries (JSON array)
    search_queries JSONB,
    
    -- Audience demographics (JSON)
    demographics JSONB,
    
    created_at TIMESTAMP DEFAULT NOW(),
    
    -- One snapshot per platform per day
    UNIQUE(platform, snapshot_date)
);

-- Indexes for common queries
CREATE INDEX idx_social_posts_platform ON social_posts(platform);
CREATE INDEX idx_social_posts_posted_at ON social_posts(posted_at DESC);
CREATE INDEX idx_social_posts_platform_post_id ON social_posts(platform, platform_post_id);
CREATE INDEX idx_social_snapshots_platform_date ON social_account_snapshots(platform, snapshot_date DESC);

-- Comments
COMMENT ON TABLE social_posts IS 'Individual social media post analytics (manual entry for now, API later)';
COMMENT ON TABLE social_account_snapshots IS 'Account-level metrics snapshots for trend tracking';
