CREATE TABLE IF NOT EXISTS plans (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    slug VARCHAR(100) UNIQUE NOT NULL,
    price_cents INT DEFAULT 0,
    currency CHAR(3) DEFAULT 'CAD',
    billing_interval ENUM('one_time','monthly','yearly') DEFAULT 'monthly',
    description TEXT NULL,
    is_active TINYINT(1) DEFAULT 1,
    sort_order INT DEFAULT 10,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS plan_features (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    plan_id BIGINT UNSIGNED NOT NULL,
    feature_key VARCHAR(150) NOT NULL,
    feature_label VARCHAR(191) NOT NULL,
    feature_value VARCHAR(191) NULL,
    created_at TIMESTAMP NULL,
    INDEX idx_plan_features_key (feature_key),
    CONSTRAINT fk_plan_features_plan FOREIGN KEY (plan_id) REFERENCES plans(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS user_subscriptions (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    plan_id BIGINT UNSIGNED NOT NULL,
    status ENUM('active','past_due','cancelled','expired') DEFAULT 'active',
    starts_at DATETIME NULL,
    ends_at DATETIME NULL,
    payment_provider VARCHAR(50) NULL,
    provider_subscription_id VARCHAR(191) NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    INDEX idx_user_subscriptions_user (user_id, status),
    CONSTRAINT fk_subscriptions_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    CONSTRAINT fk_subscriptions_plan FOREIGN KEY (plan_id) REFERENCES plans(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS news_sources (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(191) NOT NULL,
    source_type ENUM('api','rss','manual') DEFAULT 'api',
    base_url VARCHAR(255) NULL,
    api_key_name VARCHAR(191) NULL,
    is_active TINYINT(1) DEFAULT 1,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    UNIQUE KEY unique_news_source_name (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS sports_news (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    sport ENUM('nba','nhl','mlb') NOT NULL,
    source_id BIGINT UNSIGNED NULL,
    title VARCHAR(255) NOT NULL,
    slug VARCHAR(255) UNIQUE NOT NULL,
    excerpt TEXT NULL,
    source_url VARCHAR(500) NULL,
    image_url VARCHAR(500) NULL,
    published_at DATETIME NULL,
    fantasy_impact_score INT DEFAULT 0,
    fantasy_summary TEXT NULL,
    impact_tag VARCHAR(100) DEFAULT 'Fantasy Impact',
    status ENUM('draft','published','hidden') DEFAULT 'published',
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    INDEX idx_news_sport_date (sport, published_at),
    INDEX idx_news_impact (fantasy_impact_score),
    CONSTRAINT fk_news_source FOREIGN KEY (source_id) REFERENCES news_sources(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS news_entities (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    news_id BIGINT UNSIGNED NOT NULL,
    entity_type ENUM('player','team','league') NOT NULL,
    entity_id BIGINT UNSIGNED NULL,
    entity_name VARCHAR(191) NOT NULL,
    created_at TIMESTAMP NULL,
    INDEX idx_news_entities_type (entity_type, entity_name),
    CONSTRAINT fk_news_entities_news FOREIGN KEY (news_id) REFERENCES sports_news(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS trend_snapshots (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    sport ENUM('nba','nhl','mlb') NOT NULL,
    trend_type VARCHAR(60) NOT NULL,
    title VARCHAR(191) NOT NULL,
    summary TEXT NULL,
    score INT DEFAULT 0,
    entity_name VARCHAR(191) NULL,
    entity_type VARCHAR(60) NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    INDEX idx_trend_sport_score (sport, score),
    UNIQUE KEY unique_trend_title (sport, title)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS user_alert_preferences (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL UNIQUE,
    injury_alerts TINYINT(1) DEFAULT 1,
    lineup_alerts TINYINT(1) DEFAULT 1,
    news_alerts TINYINT(1) DEFAULT 1,
    trend_alerts TINYINT(1) DEFAULT 1,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    CONSTRAINT fk_alerts_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


INSERT INTO news_sources (name, source_type, base_url, api_key_name, is_active, created_at, updated_at) VALUES
('Manual Editorial Desk','manual','#',NULL,1,NOW(),NOW()),
('Demo Sports Data Feed','api','#','SPORTS_API_KEY',1,NOW(),NOW())
ON DUPLICATE KEY UPDATE name = name;

INSERT INTO plans (name, slug, price_cents, currency, billing_interval, description, is_active, sort_order, created_at, updated_at) VALUES
('Free Fan','free-fan',0,'CAD','monthly','Public leagues, core community, basic news, and starter rewards.',1,10,NOW(),NOW()),
('Verified Fan','verified-fan',100,'CAD','one_time','One-time account validation layer for trust, verified badge, and rewards wallet access.',1,20,NOW(),NOW()),
('Fan Pro','fan-pro',499,'CAD','monthly','More leagues, advanced stats, alerts, trends, and fantasy-impact news.',1,30,NOW(),NOW()),
('Commissioner Pro','commissioner-pro',999,'CAD','monthly','Private league tools, custom scoring, draft controls, trade settings, and branded league features.',1,40,NOW(),NOW()),
('Club / Brand','club-brand',2999,'CAD','monthly','Branded rooms, sponsor placements, advanced moderation, and community growth tools.',1,50,NOW(),NOW())
ON DUPLICATE KEY UPDATE price_cents = VALUES(price_cents), description = VALUES(description), sort_order = VALUES(sort_order), updated_at = NOW();

INSERT INTO plan_features (plan_id, feature_key, feature_label, feature_value, created_at)
SELECT p.id, f.feature_key, f.feature_label, f.feature_value, NOW()
FROM plans p
JOIN (
    SELECT 'free-fan' slug, 'max_leagues' feature_key, 'Active Leagues' feature_label, '3' feature_value UNION ALL
    SELECT 'free-fan','can_view_basic_news','Basic News','true' UNION ALL
    SELECT 'verified-fan','verified_badge','Verified Badge','true' UNION ALL
    SELECT 'verified-fan','rewards_wallet','Rewards Wallet','true' UNION ALL
    SELECT 'verified-fan','max_leagues','Active Leagues','5' UNION ALL
    SELECT 'fan-pro','max_leagues','Active Leagues','25' UNION ALL
    SELECT 'fan-pro','can_access_advanced_stats','Advanced Stats','true' UNION ALL
    SELECT 'fan-pro','can_access_ai_fantasy_impact','Fantasy Impact Alerts','true' UNION ALL
    SELECT 'fan-pro','can_schedule_news_alerts','News Alerts','true' UNION ALL
    SELECT 'commissioner-pro','max_leagues','Active Leagues','50' UNION ALL
    SELECT 'commissioner-pro','can_create_private_leagues','Private Leagues','true' UNION ALL
    SELECT 'commissioner-pro','can_use_custom_scoring','Custom Scoring','true' UNION ALL
    SELECT 'commissioner-pro','can_use_draft_room','Draft Room','true' UNION ALL
    SELECT 'commissioner-pro','can_export_league_data','League Exports','true' UNION ALL
    SELECT 'club-brand','max_leagues','Active Leagues','unlimited' UNION ALL
    SELECT 'club-brand','can_brand_community_room','Branded Rooms','true' UNION ALL
    SELECT 'club-brand','sponsor_posts','Sponsor Posts','true' UNION ALL
    SELECT 'club-brand','advanced_moderation','Advanced Moderation','true'
) f ON f.slug = p.slug
WHERE NOT EXISTS (SELECT 1 FROM plan_features pf WHERE pf.plan_id = p.id AND pf.feature_key = f.feature_key);

INSERT INTO sports_news (sport, title, slug, excerpt, source_url, published_at, fantasy_impact_score, fantasy_summary, impact_tag, status, created_at, updated_at) VALUES
('nba','NBA injury watch: fantasy managers monitor late lineup changes','nba-injury-watch-fantasy-managers-monitor-late-lineup-changes','Daily injury reports can shift fantasy value quickly. Watch backup minutes, usage rate, and matchup pace before locking lineups.','#',NOW(),82,'If a high-usage player sits, monitor bench players with increased minutes and usage. Treat this as a start/sit watch item.','Start/Sit Watch','published',NOW(),NOW()),
('nba','NBA waiver radar: high-minutes role players gaining attention','nba-waiver-radar-high-minutes-role-players-gaining-attention','Players with steady minutes, rebounding chances, or increased assist usage can become useful weekly streamers.','#',NOW(),71,'Target short-term pickups with minutes security and a fantasy-friendly schedule.','Waiver Wire','published',NOW(),NOW()),
('nhl','NHL goalie starts remain key for weekly fantasy matchups','nhl-goalie-starts-remain-key-for-weekly-fantasy-matchups','Confirmed starters, back-to-back schedules, and team defensive form can change goalie value before puck drop.','#',NOW(),79,'Confirmed starters are high-impact alerts. Prioritize save volume, opponent quality, and win probability.','Goalie Watch','published',NOW(),NOW()),
('nhl','NHL power-play movement creates new fantasy value','nhl-power-play-movement-creates-new-fantasy-value','Second-unit players moving to top power-play groups can become short-term pickups in deeper leagues.','#',NOW(),68,'Power-play promotion can increase shots, assists, and goal exposure. Add to watchlist.','Power Play','published',NOW(),NOW()),
('mlb','MLB pitching matchups drive streamer decisions this week','mlb-pitching-matchups-drive-streamer-decisions-this-week','Projected starters, park factors, and opponent strikeout rates matter when choosing short-term pitching help.','#',NOW(),76,'Streamer pitchers should be judged by matchup, pitch count, park, and opponent strikeout tendency.','Pitching Edge','published',NOW(),NOW()),
('mlb','MLB hot bats trend upward after lineup promotion','mlb-hot-bats-trend-upward-after-lineup-promotion','Lineup spot changes can create more plate appearances, run opportunities, and RBI chances for fantasy users.','#',NOW(),73,'Lineup promotion creates more volume. Monitor batted-ball quality and schedule strength.','Hot Bats','published',NOW(),NOW())
ON DUPLICATE KEY UPDATE fantasy_impact_score = VALUES(fantasy_impact_score), fantasy_summary = VALUES(fantasy_summary), updated_at = NOW();

INSERT INTO trend_snapshots (sport, trend_type, title, summary, score, entity_name, entity_type, created_at, updated_at) VALUES
('nba','player','NBA Guard Usage Spike','A guard profile is trending because of extra minutes and increased ball-handling responsibility.',86,'Usage Guard','player',NOW(),NOW()),
('nba','injury','NBA Questionable Tags','Late status changes are driving start/sit discussion before tipoff.',81,'Injury Watch','player',NOW(),NOW()),
('nhl','goalie','NHL Confirmed Starters','Goalie-start confirmations are creating the strongest fantasy movement.',84,'Goalie Watch','player',NOW(),NOW()),
('nhl','player','NHL Power-Play Adds','Power-play movement is creating short-term value in deeper leagues.',73,'Power Play Skater','player',NOW(),NOW()),
('mlb','pitcher','MLB Streamer Arms','Pitching matchups are trending for weekly lineup construction.',79,'Streamer Pitcher','player',NOW(),NOW()),
('mlb','player','MLB Hot Bat Lineup Boost','A hitter moving higher in the lineup is gaining fantasy attention.',74,'Hot Bat','player',NOW(),NOW())
ON DUPLICATE KEY UPDATE summary = VALUES(summary), score = VALUES(score), updated_at = NOW();
