CREATE TABLE IF NOT EXISTS users (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(191) NOT NULL,
    email VARCHAR(191) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    role ENUM('user','moderator','admin','super_admin') DEFAULT 'user',
    is_verified TINYINT(1) DEFAULT 0,
    verified_at DATETIME NULL,
    validation_payment_id VARCHAR(191) NULL,
    email_verified_at DATETIME NULL,
    last_login_at DATETIME NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS user_profiles (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL UNIQUE,
    display_name VARCHAR(191) NULL,
    bio TEXT NULL,
    avatar_url VARCHAR(255) NULL,
    favorite_sport ENUM('nba','nhl','mlb','mls') DEFAULT 'nba',
    favorite_team VARCHAR(191) NULL,
    xp_points INT DEFAULT 0,
    reward_credits INT DEFAULT 0,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    CONSTRAINT fk_profiles_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS validation_payments (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    provider VARCHAR(50) DEFAULT 'demo',
    provider_reference VARCHAR(191) NOT NULL,
    amount_cents INT NOT NULL DEFAULT 100,
    currency CHAR(3) NOT NULL DEFAULT 'CAD',
    status ENUM('pending','paid','failed','refunded','cancelled') DEFAULT 'pending',
    raw_payload JSON NULL,
    paid_at DATETIME NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    INDEX idx_validation_user (user_id),
    UNIQUE KEY unique_validation_reference (provider_reference),
    CONSTRAINT fk_validation_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS teams (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    sport ENUM('nba','nhl','mlb','mls') NOT NULL,
    name VARCHAR(191) NOT NULL,
    city VARCHAR(191) NULL,
    abbr VARCHAR(10) NULL,
    logo_url VARCHAR(255) NULL,
    external_id VARCHAR(100) NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    INDEX idx_teams_sport (sport),
    UNIQUE KEY unique_team_external (sport, external_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS players (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    sport ENUM('nba','nhl','mlb','mls') NOT NULL,
    team_id BIGINT UNSIGNED NULL,
    name VARCHAR(191) NOT NULL,
    position VARCHAR(30) NULL,
    jersey_number VARCHAR(10) NULL,
    status ENUM('active','injured','inactive','free_agent') DEFAULT 'active',
    external_id VARCHAR(100) NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    INDEX idx_players_sport (sport),
    INDEX idx_players_team (team_id),
    CONSTRAINT fk_players_team FOREIGN KEY (team_id) REFERENCES teams(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS games (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    sport ENUM('nba','nhl','mlb','mls') NOT NULL,
    external_id VARCHAR(100) NULL,
    home_team_id BIGINT UNSIGNED NULL,
    away_team_id BIGINT UNSIGNED NULL,
    scheduled_at DATETIME NOT NULL,
    status ENUM('scheduled','live','final','postponed','cancelled') DEFAULT 'scheduled',
    status_detail VARCHAR(191) NULL,
    home_score INT DEFAULT 0,
    away_score INT DEFAULT 0,
    period INT DEFAULT 0,
    game_clock VARCHAR(50) NULL,
    venue VARCHAR(191) NULL,
    external_url VARCHAR(500) NULL,
    provider VARCHAR(50) DEFAULT 'demo',
    provider_payload JSON NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    INDEX idx_games_sport_date (sport, scheduled_at),
    UNIQUE KEY unique_sport_external_game (sport, external_id),
    CONSTRAINT fk_games_home_team FOREIGN KEY (home_team_id) REFERENCES teams(id) ON DELETE SET NULL,
    CONSTRAINT fk_games_away_team FOREIGN KEY (away_team_id) REFERENCES teams(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS player_stats (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    game_id BIGINT UNSIGNED NOT NULL,
    player_id BIGINT UNSIGNED NOT NULL,
    sport ENUM('nba','nhl','mlb','mls') NOT NULL,
    stats_json JSON NOT NULL,
    fantasy_points DECIMAL(8,2) DEFAULT 0,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    UNIQUE KEY unique_game_player (game_id, player_id),
    CONSTRAINT fk_stats_game FOREIGN KEY (game_id) REFERENCES games(id) ON DELETE CASCADE,
    CONSTRAINT fk_stats_player FOREIGN KEY (player_id) REFERENCES players(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS fantasy_leagues (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    commissioner_id BIGINT UNSIGNED NOT NULL,
    sport ENUM('nba','nhl','mlb','mls') NOT NULL,
    name VARCHAR(191) NOT NULL,
    slug VARCHAR(191) UNIQUE NOT NULL,
    visibility ENUM('public','private','invite_only') DEFAULT 'public',
    league_type ENUM('season','weekly','daily','challenge') DEFAULT 'season',
    scoring_type ENUM('standard','custom') DEFAULT 'standard',
    max_members INT DEFAULT 12,
    require_verified TINYINT(1) DEFAULT 0,
    randomizer_enabled TINYINT(1) DEFAULT 1,
    randomizer_seed VARCHAR(64) NULL,
    invite_code VARCHAR(24) NULL,
    league_theme JSON NULL,
    ai_optimized TINYINT(1) DEFAULT 0,
    ai_config_json JSON NULL,
    draft_type ENUM('snake','auto','manual') DEFAULT 'snake',
    draft_starts_at DATETIME NULL,
    season_year INT NOT NULL,
    status ENUM('setup','drafting','active','completed','archived') DEFAULT 'setup',
    scoring_rules JSON NULL,
    scoring_preset VARCHAR(100) DEFAULT 'standard',
    weekly_lock_day VARCHAR(20) NULL,
    allow_auto_lineup TINYINT(1) DEFAULT 0,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    INDEX idx_leagues_sport (sport),
    UNIQUE KEY unique_invite_code (invite_code),
    CONSTRAINT fk_leagues_commissioner FOREIGN KEY (commissioner_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS fantasy_league_members (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    league_id BIGINT UNSIGNED NOT NULL,
    user_id BIGINT UNSIGNED NOT NULL,
    team_name VARCHAR(191) NOT NULL,
    team_slug VARCHAR(191) NULL,
    team_city VARCHAR(100) NULL,
    team_mascot VARCHAR(100) NULL,
    team_primary_color VARCHAR(20) NULL,
    team_secondary_color VARCHAR(20) NULL,
    team_logo_text VARCHAR(10) NULL,
    randomizer_seed VARCHAR(64) NULL,
    validation_status ENUM('pending','validated','rejected') DEFAULT 'validated',
    role ENUM('commissioner','member') DEFAULT 'member',
    joined_at DATETIME NULL,
    UNIQUE KEY unique_league_user (league_id, user_id),
    CONSTRAINT fk_members_league FOREIGN KEY (league_id) REFERENCES fantasy_leagues(id) ON DELETE CASCADE,
    CONSTRAINT fk_members_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS league_draft_orders (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    league_id BIGINT UNSIGNED NOT NULL,
    member_id BIGINT UNSIGNED NOT NULL,
    user_id BIGINT UNSIGNED NOT NULL,
    draft_position INT NOT NULL,
    randomized_at DATETIME NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    UNIQUE KEY unique_league_member_order (league_id, member_id),
    INDEX idx_draft_order_lookup (league_id, draft_position),
    CONSTRAINT fk_draft_order_league FOREIGN KEY (league_id) REFERENCES fantasy_leagues(id) ON DELETE CASCADE,
    CONSTRAINT fk_draft_order_member FOREIGN KEY (member_id) REFERENCES fantasy_league_members(id) ON DELETE CASCADE,
    CONSTRAINT fk_draft_order_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS fantasy_rosters (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    league_id BIGINT UNSIGNED NOT NULL,
    user_id BIGINT UNSIGNED NOT NULL,
    player_id BIGINT UNSIGNED NOT NULL,
    position VARCHAR(20) NULL,
    roster_status ENUM('active','bench','injured','waiver','dropped') DEFAULT 'active',
    acquired_type ENUM('draft','waiver','trade','admin') DEFAULT 'draft',
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    INDEX idx_roster_lookup (league_id, user_id),
    CONSTRAINT fk_rosters_league FOREIGN KEY (league_id) REFERENCES fantasy_leagues(id) ON DELETE CASCADE,
    CONSTRAINT fk_rosters_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    CONSTRAINT fk_rosters_player FOREIGN KEY (player_id) REFERENCES players(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS fantasy_lineups (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    league_id BIGINT UNSIGNED NOT NULL,
    user_id BIGINT UNSIGNED NOT NULL,
    scoring_period VARCHAR(50) NOT NULL,
    lineup_json JSON NOT NULL,
    locked_at DATETIME NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    INDEX idx_lineups_period (league_id, scoring_period)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS fantasy_scores (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    league_id BIGINT UNSIGNED NOT NULL,
    user_id BIGINT UNSIGNED NOT NULL,
    scoring_period VARCHAR(50) NOT NULL,
    fantasy_points DECIMAL(10,2) DEFAULT 0,
    rank_position INT NULL,
    finalized_at DATETIME NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    UNIQUE KEY unique_score_period (league_id, user_id, scoring_period)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS community_rooms (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    sport ENUM('nba','nhl','mlb','mls') NULL,
    team_id BIGINT UNSIGNED NULL,
    name VARCHAR(191) NOT NULL,
    slug VARCHAR(191) UNIQUE NOT NULL,
    description VARCHAR(255) NULL,
    is_active TINYINT(1) DEFAULT 1,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    CONSTRAINT fk_rooms_team FOREIGN KEY (team_id) REFERENCES teams(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS community_posts (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    room_id BIGINT UNSIGNED NULL,
    league_id BIGINT UNSIGNED NULL,
    post_type ENUM('text','image','poll','prediction','trade_block','lineup_help') DEFAULT 'text',
    content TEXT NOT NULL,
    media_url VARCHAR(255) NULL,
    status ENUM('published','hidden','flagged','deleted') DEFAULT 'published',
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    INDEX idx_posts_status (status, created_at),
    CONSTRAINT fk_posts_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    CONSTRAINT fk_posts_room FOREIGN KEY (room_id) REFERENCES community_rooms(id) ON DELETE SET NULL,
    CONSTRAINT fk_posts_league FOREIGN KEY (league_id) REFERENCES fantasy_leagues(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS community_comments (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    post_id BIGINT UNSIGNED NOT NULL,
    user_id BIGINT UNSIGNED NOT NULL,
    parent_id BIGINT UNSIGNED NULL,
    content TEXT NOT NULL,
    status ENUM('published','hidden','flagged','deleted') DEFAULT 'published',
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    CONSTRAINT fk_comments_post FOREIGN KEY (post_id) REFERENCES community_posts(id) ON DELETE CASCADE,
    CONSTRAINT fk_comments_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS community_reactions (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    post_id BIGINT UNSIGNED NOT NULL,
    user_id BIGINT UNSIGNED NOT NULL,
    reaction_type VARCHAR(30) DEFAULT 'like',
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    UNIQUE KEY unique_post_reaction (post_id, user_id),
    CONSTRAINT fk_reactions_post FOREIGN KEY (post_id) REFERENCES community_posts(id) ON DELETE CASCADE,
    CONSTRAINT fk_reactions_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS points_ledger (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    source_type VARCHAR(100) NOT NULL,
    source_id BIGINT UNSIGNED NULL,
    points INT NOT NULL,
    description VARCHAR(255) NULL,
    created_at TIMESTAMP NULL,
    INDEX idx_points_user (user_id),
    CONSTRAINT fk_points_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS rewards (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(191) NOT NULL,
    description TEXT NULL,
    reward_type ENUM('badge','theme','discount','feature','digital_item') NOT NULL,
    points_cost INT DEFAULT 0,
    stock INT NULL,
    is_active TINYINT(1) DEFAULT 1,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS reward_redemptions (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    reward_id BIGINT UNSIGNED NOT NULL,
    points_spent INT NOT NULL,
    status ENUM('pending','approved','fulfilled','rejected') DEFAULT 'pending',
    notes TEXT NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    CONSTRAINT fk_redemptions_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    CONSTRAINT fk_redemptions_reward FOREIGN KEY (reward_id) REFERENCES rewards(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS notifications (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    title VARCHAR(191) NOT NULL,
    body TEXT NULL,
    action_url VARCHAR(255) NULL,
    read_at DATETIME NULL,
    created_at TIMESTAMP NULL,
    CONSTRAINT fk_notifications_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS api_sync_logs (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    provider VARCHAR(100) NOT NULL,
    sport ENUM('nba','nhl','mlb','mls') NULL,
    status ENUM('success','warning','failed') DEFAULT 'success',
    message VARCHAR(255) NULL,
    created_at TIMESTAMP NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS settings (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    setting_key VARCHAR(191) UNIQUE NOT NULL,
    setting_value TEXT NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


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','mls') NOT NULL,
    source_id BIGINT UNSIGNED NULL,
    external_id VARCHAR(150) NULL,
    source_provider VARCHAR(80) NULL,
    source_name VARCHAR(191) 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',
    discussion_prompt VARCHAR(255) NULL,
    raw_payload JSON NULL,
    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),
    UNIQUE KEY unique_news_external (sport, external_id),
    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','mls') 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;

-- FanLeague Arena v1.3 Full Feeds, Automated News, AI League Builder, and Community Enhancements.
-- Safe to run through public/upgrade/v1_3.php. Duplicate column/key warnings are ignored by the upgrader.



CREATE TABLE IF NOT EXISTS game_feeds (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    game_id BIGINT UNSIGNED NOT NULL,
    sport ENUM('nba','nhl','mlb','mls') NOT NULL,
    external_id VARCHAR(100) NOT NULL,
    feed_type VARCHAR(50) DEFAULT 'summary',
    headline VARCHAR(255) NULL,
    summary TEXT NULL,
    source_url VARCHAR(500) NULL,
    payload_json JSON NULL,
    fetched_at DATETIME NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    UNIQUE KEY unique_game_feed_type (game_id, feed_type),
    INDEX idx_game_feeds_sport (sport, fetched_at),
    CONSTRAINT fk_game_feeds_game FOREIGN KEY (game_id) REFERENCES games(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS game_feed_leaders (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    game_id BIGINT UNSIGNED NOT NULL,
    sport ENUM('nba','nhl','mlb','mls') NOT NULL,
    category VARCHAR(100) NOT NULL,
    player_name VARCHAR(191) NOT NULL,
    display_value VARCHAR(191) NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    UNIQUE KEY unique_game_leader (game_id, category, player_name),
    CONSTRAINT fk_game_leaders_game FOREIGN KEY (game_id) REFERENCES games(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS league_ai_suggestions (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    user_id BIGINT UNSIGNED NOT NULL,
    sport ENUM('nba','nhl','mlb','mls') NOT NULL,
    suggested_name VARCHAR(191) NOT NULL,
    config_json JSON NOT NULL,
    accepted_at DATETIME NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    INDEX idx_ai_suggestions_user (user_id, created_at),
    CONSTRAINT fk_ai_suggestions_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS community_room_members (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    room_id BIGINT UNSIGNED NOT NULL,
    user_id BIGINT UNSIGNED NOT NULL,
    role ENUM('member','moderator','owner') DEFAULT 'member',
    joined_at DATETIME NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    UNIQUE KEY unique_room_user (room_id, user_id),
    CONSTRAINT fk_room_members_room FOREIGN KEY (room_id) REFERENCES community_rooms(id) ON DELETE CASCADE,
    CONSTRAINT fk_room_members_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS community_bookmarks (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    post_id BIGINT UNSIGNED NOT NULL,
    user_id BIGINT UNSIGNED NOT NULL,
    created_at TIMESTAMP NULL,
    UNIQUE KEY unique_bookmark (post_id, user_id),
    CONSTRAINT fk_bookmarks_post FOREIGN KEY (post_id) REFERENCES community_posts(id) ON DELETE CASCADE,
    CONSTRAINT fk_bookmarks_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS community_reports (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    post_id BIGINT UNSIGNED NOT NULL,
    user_id BIGINT UNSIGNED NOT NULL,
    reason VARCHAR(191) NOT NULL,
    notes TEXT NULL,
    status ENUM('open','reviewed','dismissed','actioned') DEFAULT 'open',
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL,
    INDEX idx_reports_status (status, created_at),
    CONSTRAINT fk_reports_post FOREIGN KEY (post_id) REFERENCES community_posts(id) ON DELETE CASCADE,
    CONSTRAINT fk_reports_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO settings (setting_key, setting_value, created_at, updated_at) VALUES
('espn_full_feed_enabled','true',NOW(),NOW()),
('espn_news_auto_sync_enabled','true',NOW(),NOW()),
('ai_league_builder_enabled','true',NOW(),NOW()),
('community_rooms_enabled','true',NOW(),NOW()),
('v1_3_upgrade_installed_at',DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s'),NOW(),NOW())
ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = NOW();

INSERT INTO community_rooms (sport, name, slug, description, is_active, created_at, updated_at) VALUES
('nba','NBA Fantasy Lab','nba-fantasy-lab','Hoops trends, lineups, injuries, starts, sits, and waiver talk.',1,NOW(),NOW()),
('nhl','NHL Puck Room','nhl-puck-room','Goalies, power play movement, hits, blocks, and weekly fantasy debates.',1,NOW(),NOW()),
('mlb','MLB Diamond Room','mlb-diamond-room','Pitching streamers, hot bats, lineups, and matchup planning.',1,NOW(),NOW()),
('mls','MLS Matchday Lab','mls-matchday-lab','Starting XI watch, clean sheets, set pieces, and soccer fantasy-style decisions.',1,NOW(),NOW())
ON DUPLICATE KEY UPDATE description = VALUES(description), updated_at = NOW();
