const AMERICAN_SOCIAL_LEAGUES = new Set([
  'nfl',
  'nba',
  'wnba',
  'mlb',
  'nhl',
  'ncaaf',
  'ncaab',
]);

const AMERICAN_SOCIAL_SPORTS = new Set([
  'football',
  'basketball',
  'baseball',
  'hockey',
  'nfl',
  'nba',
  'wnba',
  'mlb',
  'nhl',
  'ncaaf',
  'ncaab',
]);

function normalizeValue(value: string | null | undefined): string | null {
  if (typeof value !== 'string') {
    return null;
  }

  const normalized = value.trim().toLowerCase();
  return normalized.length > 0 ? normalized : null;
}

export function isAmericanSocialLeague(league: string | null | undefined): boolean {
  const normalized = normalizeValue(league);
  return normalized !== null && AMERICAN_SOCIAL_LEAGUES.has(normalized);
}

export function isAmericanSocialSport(sport: string | null | undefined): boolean {
  const normalized = normalizeValue(sport);
  return normalized !== null && AMERICAN_SOCIAL_SPORTS.has(normalized);
}

export function isAllowedAmericanTrend(signal: {
  trend_type: string;
  sport: string | null;
  league: string | null;
  data?: Record<string, unknown>;
}): boolean {
  if (isAmericanSocialLeague(signal.league) || isAmericanSocialSport(signal.sport)) {
    return true;
  }

  if (signal.trend_type !== 'recap') {
    return false;
  }

  const games = Array.isArray(signal.data?.games) ? signal.data.games : [];
  return games.length > 0 && games.every((game) => {
    if (!game || typeof game !== 'object') {
      return false;
    }

    return isAmericanSocialLeague((game as { league?: string | null }).league);
  });
}

export function isAllowedAmericanContent(content: {
  content_type?: string | null;
  sport?: string | null;
  league?: string | null;
  source_data?: Record<string, unknown> | null;
}): boolean {
  return isAllowedAmericanTrend({
    trend_type: content.content_type || '',
    sport: content.sport || null,
    league: content.league || null,
    data: content.source_data || {},
  });
}
