export type PublicMarketSourceType = 'sportsbook' | 'feed' | 'provider' | 'unknown';

const SOURCE_TYPES: Record<string, PublicMarketSourceType> = {
  fanduel: 'sportsbook',
  draftkings: 'sportsbook',
  williamhillus: 'sportsbook',
  caesars: 'sportsbook',
  betmgm: 'sportsbook',
  espnbet: 'sportsbook',
  betrivers: 'sportsbook',
  fanatics: 'sportsbook',
  hardrockbet: 'sportsbook',
  hardrocksportsbook: 'sportsbook',
  hardrock: 'sportsbook',
  bet365: 'sportsbook',
  consensus: 'provider',
  sportsgameodds: 'feed',
  sgoauto: 'feed',
  theodds: 'feed',
  theoddsapi: 'feed',
  sgoautotheodds: 'feed',
};

function publicVerificationLabel(type: PublicMarketSourceType): string | null {
  if (type === 'sportsbook' || type === 'feed' || type === 'provider') return 'Double-verified odds';
  return null;
}

export function normalizeMarketSourceToken(value: unknown): string | null {
  const normalized = String(value || '')
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '');
  return normalized || null;
}

export function getPublicMarketSourceMeta(value: unknown): {
  source: string | null;
  label: string | null;
  type: PublicMarketSourceType;
} {
  const source = normalizeMarketSourceToken(value);
  if (!source) {
    return {
      source: null,
      label: null,
      type: 'unknown',
    };
  }

  const type = SOURCE_TYPES[source] || 'provider';
  return {
    source: type === 'feed' || type === 'provider' ? 'market' : type,
    label: publicVerificationLabel(type),
    type,
  };
}

export function hasNamedMarketSource(value: unknown): boolean {
  return getPublicMarketSourceMeta(value).source != null;
}
