-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-- Posimai Feed - Media Sources Table Migration
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-- Purpose: Store user-customizable RSS feed sources
-- Date: 2026-03-02
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

-- Create media_sources table
CREATE TABLE IF NOT EXISTS media_sources (
    id SERIAL PRIMARY KEY,
    user_id TEXT NOT NULL,                  -- User identifier (from authMiddleware)
    feed_url TEXT NOT NULL,                 -- RSS feed URL
    feed_name TEXT NOT NULL,                -- Display name (e.g., "TechCrunch")
    feed_icon TEXT,                         -- Favicon URL
    category TEXT,                          -- User-defined category (e.g., "Tech", "News")
    is_active BOOLEAN DEFAULT true,         -- Enable/disable feed without deleting
    last_fetched_at TIMESTAMP,              -- Last time articles were fetched
    fetch_interval_minutes INTEGER DEFAULT 60,  -- How often to fetch (default: 1 hour)
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW(),

    -- Prevent duplicate feeds per user
    UNIQUE(user_id, feed_url)
);

-- Create index for efficient queries
CREATE INDEX IF NOT EXISTS idx_media_sources_user_active
ON media_sources(user_id, is_active);

-- Create index for scheduled fetching
CREATE INDEX IF NOT EXISTS idx_media_sources_fetch_schedule
ON media_sources(is_active, last_fetched_at)
WHERE is_active = true;

-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-- Sample Data (Optional - for testing)
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

-- Example: Add default feeds for new users
-- INSERT INTO media_sources (user_id, feed_url, feed_name, category) VALUES
-- ('pk_maita_demo', 'https://zenn.dev/feed', 'Zenn', 'Tech'),
-- ('pk_maita_demo', 'https://qiita.com/popular-items/feed', 'Qiita', 'Tech');

-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
-- Rollback (if needed)
-- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

-- DROP TABLE IF EXISTS media_sources;
