import { ref } from 'vue';
import api from '../api';
import type { MatchPhase } from '../utils/matchPhase';

export interface DesktopParlayMatch {
  id: string;
  leagueId?: string;
  homeTeamName: string;
  awayTeamName: string;
  homeTeamCode?: string;
  awayTeamCode?: string;
  homeTeamLogoUrl?: string | null;
  awayTeamLogoUrl?: string | null;
  startTime: string;
  leagueName: string;
  leagueLogoUrl?: string | null;
  status?: string;
  bettingOpen?: boolean;
  matchPhase?: MatchPhase;
  score?: {
    htHome: number | null;
    htAway: number | null;
    ftHome: number | null;
    ftAway: number | null;
    homeCorners?: number | null;
    awayCorners?: number | null;
    homeYellowCards?: number | null;
    awayYellowCards?: number | null;
    homeRedCards?: number | null;
    awayRedCards?: number | null;
    homeCards?: number | null;
    awayCards?: number | null;
  } | null;
  markets?: unknown[];
}

const parlayMatches = ref<DesktopParlayMatch[]>([]);
const parlayLoading = ref(false);
let inflight: Promise<void> | null = null;

async function loadParlayMatches(force = false): Promise<void> {
  if (!force && parlayMatches.value.length > 0) return;
  if (inflight) return inflight;

  parlayLoading.value = true;
  inflight = (async () => {
    try {
      const { data } = await api.get('/player/matches', { params: { scope: 'parlay' } });
      parlayMatches.value = (data.data ?? []) as DesktopParlayMatch[];
    } catch {
      parlayMatches.value = [];
    } finally {
      parlayLoading.value = false;
      inflight = null;
    }
  })();

  return inflight;
}

export function useDesktopParlayMatches() {
  return {
    parlayMatches,
    parlayLoading,
    loadParlayMatches,
  };
}
