/**
 * Feeder Types - Senior Level Implementation
 * Based on actual Mackolik API responses
 */

// ============================================
// SPORT TYPES
// ============================================
export type Sport = "football" | "basketball";

export const SPORTS_CONFIG: Record<
  Sport,
  { sportParam: string; iddaaUrlPath: string }
> = {
  football: { sportParam: "Soccer", iddaaUrlPath: "mac" },
  basketball: { sportParam: "Basketball", iddaaUrlPath: "basketbol/mac" },
};

// ============================================
// MATCH STATUS TYPES
// ============================================
export type MatchStatus = "Cancelled" | "Played" | "Playing" | "Scheduled";
export type MatchState =
  | "preGame"
  | "postGame"
  | "live"
  | "liveGame"
  | "pre"
  | "post";

// ============================================
// LIVESCORES API RESPONSE
// ============================================
export interface LivescoresApiResponse {
  status: string;
  data: {
    matches: Record<string, MatchSummary>;
    competitions: Record<string, Competition>;
  };
}

export interface MatchSummary {
  id: string;
  matchName: string;
  matchSlug: string;
  competitionId: string;
  mstUtc: number;
  iddaaCode: string | number | null;
  statusBoxContent?: string | null; // ERT = Erteledendi
  substate?: string | null;
  homeTeam: {
    id: string;
    name: string;
    slug: string;
  };
  awayTeam: {
    id: string;
    name: string;
    slug: string;
  };
  score?: {
    home: number | string | null;
    away: number | string | null;
    ht?: {
      home: number | string | null;
      away: number | string | null;
    };
  };
  homeScore?: number | string | null;
  awayScore?: number | string | null;
  state?: string | null;
  status?: string | null;
  winner?: string;
}

export interface Competition {
  id: string;
  name: string;
  competitionSlug: string;
  sortOrder?: number;
  country: {
    id: string;
    name: string;
  };
}

// ============================================
// MATCH HEADER API RESPONSE
// ============================================
export interface MatchHeaderResponse {
  status: string;
  data: {
    html: string; // Contains score, status, HT score
  };
}

export interface ParsedMatchHeader {
  matchStatus: MatchState;
  scoreHome: number | null;
  scoreAway: number | null;
  htScoreHome: number | null;
  htScoreAway: number | null;
}

// ============================================
// KEY EVENTS API RESPONSE
// ============================================
export interface KeyEventsResponse {
  status: string;
  data: {
    keyEvents: RawKeyEvent[];
    matchState: MatchState;
    matchStartTime: number;
    finishedPeriodIds: number[];
  };
}

export interface RawKeyEvent {
  type: "goal" | "card" | "substitute" | "penalty-missed";
  subType: "goal" | "penalty-goal" | "yc" | "rc" | "pm" | "ps" | null;
  position: "home" | "away";
  periodId: number; // 1 = 1st half, 2 = 2nd half
  timeMin: string;
  seconds: number | null;
  playerName: string;
  playerUrl: string;
  assistPlayerName?: string | null;
  assistPlayerUrl?: string | null;
  playerOutName?: string | null;
  playerOutUrl?: string | null;
  score?: string; // "1-0" format
}

export interface TransformedEvent {
  matchId: string;
  playerId: string;
  playerName: string;
  teamId: string;
  eventType: "goal" | "card" | "substitute" | "other";
  eventSubtype: string | null;
  timeMinute: string;
  timeSeconds: number | null;
  periodId: number;
  assistPlayerId: string | null;
  assistPlayerName: string | null;
  scoreAfter: string | null;
  playerOutId: string | null;
  playerOutName: string | null;
  position: "home" | "away";
}

// ============================================
// MATCH STATS (LINEUPS) API RESPONSE
// ============================================
export interface MatchStatsResponse {
  status: string;
  data: {
    status: MatchState;
    stats: {
      home: RawPlayerStats[];
      away: RawPlayerStats[];
      homeBench?: RawPlayerStats[];
      awayBench?: RawPlayerStats[];
      homeSubstitutes?: RawPlayerStats[];
      awaySubstitutes?: RawPlayerStats[];
    };
  };
}

export interface RawPlayerStats {
  personId: string;
  matchName: string;
  shirtNumber: number | null;
  position: "goalkeeper" | "defender" | "midfielder" | "striker" | "Coach" | "";
  events: PlayerEvent[] | null;
}

export interface PlayerEvent {
  name:
    | "goal"
    | "yellow-card"
    | "red-card"
    | "sub-off"
    | "sub-on"
    | "penalty-missed";
  timeMin: string;
  count: number;
}

export interface TransformedPlayer {
  id: string;
  name: string;
  slug: string;
  teamId?: string;
}

export interface MatchParticipation {
  matchId: string;
  playerId: string;
  teamId: string;
  position: string | null;
  shirtNumber: number | null;
  isStarting: boolean;
}

// ============================================
// GAME STATS API RESPONSE
// ============================================
export interface GameStatsResponse {
  status: string;
  data: {
    status: MatchStatus;
    startTime: number;
    home: TeamGameStats;
    away: Partial<TeamGameStats>;
  };
}

export interface TeamGameStats {
  possesionPercentage?: number;
  shotsOnTarget?: number;
  shotsOffTarget?: number;
  totalPasses?: number;
  corners?: number;
  fouls?: number;
  offsides?: number;
}

export interface TransformedMatchStats {
  home: TeamGameStats;
  away: TeamGameStats;
}

// ============================================
// MANAGER API RESPONSE
// ============================================
export interface ManagerResponse {
  status: string;
  data: {
    status: MatchState;
    stats: {
      home: RawPlayerStats;
      away: RawPlayerStats;
    };
  };
}

export interface TransformedManager {
  id: string;
  name: string;
  role: string;
}

// ============================================
// IDDAA ODDS API RESPONSE (JSON Endpoint)
// ============================================
export interface IddaaOddsResponse {
  status: string;
  data: {
    matchStatus: MatchStatus;
    markets: Record<string, IddaaMarket>;
  };
}

export interface IddaaMarket {
  outcomes: Record<string, IddaaOutcome>;
  code: string;
  mbc: string;
}

export interface IddaaOutcome {
  outcome: string; // The odds value (e.g., "1.78")
  handicap: string | null;
  state: "active" | "suspended";
  label: string; // "1", "X", "2", "Alt", "Üst", etc.
}

// ============================================
// IDDAA MARKETS HTML RESPONSE
// ============================================
export interface IddaaMarketsHtmlResponse {
  status: string;
  data: {
    html: string;
    matchStatus: MatchStatus;
  };
}

export interface ParsedMarket {
  marketId: string;
  marketName: string;
  iddaaCode: string;
  mbc: string;
  selections: ParsedSelection[];
}

export interface ParsedSelection {
  shortcode: string;
  outcomeNo: string;
  label: string;
  value: string; // The odds value
}

// ============================================
// BASKETBALL BOX SCORE
// ============================================
export interface BasketballBoxScoreResponse {
  status: string;
  data: {
    views: {
      home: { html: string };
      away: { html: string };
    };
  };
}

export interface BasketballPlayerStats {
  id: string;
  name: string;
  teamId: string;
  minutes: string;
  points: number;
  rebounds: number;
  assists: number;
  steals: number;
  blocks: number;
  turnovers: number;
  fouls: number;
  fgMade: number;
  fgAttempted: number;
  threePtMade: number;
  threePtAttempted: number;
  ftMade: number;
  ftAttempted: number;
}

export interface BasketballTeamTotals {
  points?: number;
  rebounds?: number;
  assists?: number;
  steals?: number;
  blocks?: number;
  turnovers?: number;
  fouls?: number;
  fgMade?: number;
  fgAttempted?: number;
  threePtMade?: number;
  threePtAttempted?: number;
  ftMade?: number;
  ftAttempted?: number;
  q1?: number | null;
  q2?: number | null;
  q3?: number | null;
  q4?: number | null;
  ot?: number | null;
}

export interface BasketballTeamStats {
  home: BasketballTeamTotals;
  away: BasketballTeamTotals;
}

// ============================================
// MATCH OFFICIALS
// ============================================
export interface MatchOfficial {
  name: string;
  role: string;
}

export interface DbEventPayload {
  match_id: string;
  player_id: string;
  team_id: string;
  event_type: "goal" | "card" | "substitute";
  event_subtype: string | null;
  time_minute: string;
  time_seconds: number | null;
  period_id: number;
  assist_player_id: string | null;
  score_after: string | null;
  player_out_id: string | null;
  position: "home" | "away";
}

export interface DbMarketSelectionPayload {
  shortcode: string;
  name: string;
  odd: string;
  position: string;
}

export interface DbMarketPayload {
  id: string;
  name: string;
  iddaaCode: string;
  mbc: string;
  selectionCollection: DbMarketSelectionPayload[];
}

// ============================================
// MARKET MAPPING (Static)
// ============================================
export const MARKET_MAPPING: Record<string, string> = {
  // Ana Bahisler
  "1": "Maç Sonucu",
  "3": "Çifte Şans",
  "6-11": "Handikaplı MS (0:1)",
  "6-22": "Handikaplı MS (0:2)",
  "611": "Handikaplı MS (1:0)",
  "622": "Handikaplı MS (2:0)",
  "14": "İlk Yarı / Maç Sonucu",
  "15": "Maç Skoru",

  // Gol Alt/Üst
  "180.5": "0.5 Alt/Üst",
  "181.5": "1.5 Alt/Üst",
  "182.5": "2.5 Alt/Üst",
  "183.5": "3.5 Alt/Üst",
  "184.5": "4.5 Alt/Üst",
  "185.5": "5.5 Alt/Üst",

  // Diğer Gol Bahisleri
  "11": "Karşılıklı Gol",
  "12": "Tek / Çift",
  "24": "İlk Golü Kim Atar",
  "26": "Toplam Gol Aralığı",
  "32": "En Çok Gol Olacak Yarı",

  // Yarı Bahisleri
  "4": "1. Yarı Sonucu",
  "5": "1. Yarı Çifte Şans",
  "54": "2. Yarı Sonucu",
  "190.5": "1. Yarı 0.5 Alt/Üst",
  "191.5": "1. Yarı 1.5 Alt/Üst",
  "192.5": "1. Yarı 2.5 Alt/Üst",
  "39": "1. Yarı Karşılıklı Gol",

  // Takım Bahisleri
  "280.5": "Ev Sahibi 0.5 Alt/Üst",
  "281.5": "Ev Sahibi 1.5 Alt/Üst",
  "282.5": "Ev Sahibi 2.5 Alt/Üst",
  "283.5": "Ev Sahibi 3.5 Alt/Üst",
  "290.5": "Deplasman 0.5 Alt/Üst",
  "291.5": "Deplasman 1.5 Alt/Üst",
  "292.5": "Deplasman 2.5 Alt/Üst",
  "400.5": "1. Yarı Ev Sahibi 0.5 Alt/Üst",
  "430.5": "1. Yarı Deplasman 0.5 Alt/Üst",
  "37": "Ev Sahibi Gol Yemeden Kazanır",
  "38": "Deplasman Gol Yemeden Kazanır",

  // Korner & Kart
  "47": "En Çok Korner",
  "48": "1. Yarı En Çok Korner",
  "49": "İlk Korner",
  "43": "Toplam Korner Aralığı",
  "44": "1. Yarı Korner Aralığı",
  "463.5": "1. Yarı 3.5 Korner Alt/Üst",
  "464.5": "1. Yarı 4.5 Korner Alt/Üst",
  "465.5": "1. Yarı 5.5 Korner Alt/Üst",
  "53": "Kırmızı Kart Olur mu?",
  "384.5": "4.5 Kart Puanı Alt/Üst",
  "385.5": "5.5 Kart Puanı Alt/Üst",
  "386.5": "6.5 Kart Puanı Alt/Üst",

  // Kombine
  "301.5": "MS ve 1.5 Alt/Üst",
  "302.5": "MS ve 2.5 Alt/Üst",
  "303.5": "MS ve 3.5 Alt/Üst",
  "304.5": "MS ve 4.5 Alt/Üst",

  // İki Yarıyı da Kazanır (39 conflicts with 1. Yarı Karşılıklı Gol, keep that one)
  "40": "Deplasman İki Yarıyı da Kazanır",
};

// ============================================
// AXIOS CONFIG
// ============================================
export interface AxiosRequestConfig {
  headers: {
    "User-Agent": string;
    Referer: string;
    "X-Requested-With": string;
    "Accept-Language"?: string;
  };
  timeout: number;
}

export const DEFAULT_HEADERS = {
  "User-Agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
  Referer: "https://www.mackolik.com/",
  "X-Requested-With": "XMLHttpRequest",
  "Accept-Language": "tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7",
};

export const DEFAULT_TIMEOUT = 30000;

// ============================================
// SIDELINED PLAYERS API RESPONSE
// ============================================
export interface SidelinedResponse {
  homeTeam: SidelinedTeamData;
  awayTeam: SidelinedTeamData;
}

export interface SidelinedTeamData {
  teamName: string;
  teamId: string;
  totalSidelined: number;
  players: SidelinedPlayer[];
}

export interface SidelinedPlayer {
  playerId: string;
  playerName: string;
  playerUrl: string;
  position: string;
  positionShort: string;
  type: "injury" | "suspension" | "other";
  description: string;
  matchesMissed: number | null;
  average: number | null;
  reasonIcon: string;
}

// ============================================
// PROCESSING RESULT
// ============================================
export interface ProcessResult {
  success: boolean;
  retryable: boolean;
  error?: string;
}
