import {
  BASE_URL,
  forceLogout,
  GAMES_BASE_URL,
  parseJsonOrLogout,
  X_API_KEY,
} from "@/constants";

const DEFAULT_HEADERS = {
  Accept: "application/json",
  "Content-Type": "application/json",
  "x-api-key": X_API_KEY,
};

export async function fetchSports() {
  const res = await fetch(`${GAMES_BASE_URL}/sports`, {
    method: "GET",
    headers: DEFAULT_HEADERS,
    cache: "no-store",
  });
  return parseJsonOrLogout(res);
}

export async function fetchLeagues() {
  const res = await fetch(`${GAMES_BASE_URL}/leagues`, {
    method: "GET",
    headers: DEFAULT_HEADERS,
    cache: "no-store",
  });

  return parseJsonOrLogout(res);
}

export const fetchEvents = async (sportID?: string, live?: boolean) => {
  const params = new URLSearchParams();

  if (sportID) {
    params.append("sportID", sportID);
  }

  if (live !== undefined) {
    params.append("live", String(live));
  }

  const url = `${GAMES_BASE_URL}/events${
    params.toString() ? `?${params.toString()}` : ""
  }`;

  const res = await fetch(url, {
    method: "GET",
    headers: DEFAULT_HEADERS,
    cache: "no-store",
  });

  return parseJsonOrLogout(res);
};

export async function fetchTeams() {
  const res = await fetch(`${BASE_URL}/api/get-teams`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    cache: "no-store",
  });

  const data = await res.json();
  if (!res.ok) {
    forceLogout();
    throw new Error(`Faild to fetch teams (${res.status})`);
  }
  return data;
}

export async function fetchPlayers() {
  const res = await fetch(`${BASE_URL}/api/get-players`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    cache: "no-store",
  });
  const data = await res.json();
  if (!res.ok) {
    forceLogout();
    throw new Error(`Failed to fetch Players (${res.status})`);
  }
  return data;
}

export const fetchStats = async () => {
  const res = await fetch(`${BASE_URL}/api/get-stats`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    cache: "no-store",
  });
  const data = await res.json();
  if (!res.ok) {
    // forceLogout();
    throw new Error(`Failed to fetch Stats (${res.status})`);
  }
  return data;
};

export const fetchBets = async (user_id: any, token: any) => {
  const res = await fetch(`${BASE_URL}/api/get-bet`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({
      user_id,
    }),
    cache: "no-store",
  });
  const data = await res.json();
  if (!res.ok) {
    forceLogout();
    throw new Error(`Failed to fetch Bets (${res.status})`);
  }
  return data;
};

export const placeBet = async (
  user_id: string,
  token: string,
  event_id: string,
  teamId: string,
  cards: number[],
  bet_odd: string
) => {
  const params = new URLSearchParams({
    user_id,
    event_id,
    teamId,
    cards: JSON.stringify(cards),
    bet_odd
  });

  const res = await fetch(`${BASE_URL}/api/place-bet?${params.toString()}`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      // Content-Type optional since no JSON body
    },
    // body: "{}", // optional, usually not needed
    cache: "no-store",
  });

  const text = await res.text(); // 👈 error debugging ke liye
  if (!res.ok) {
    forceLogout();

    throw new Error(text || `Failed to place bet (${res.status})`);
  }

  return text ? JSON.parse(text) : {};
};

// postman request 'https://api.sportsgameodds.com/v2/events/?sportID=BASKETBALL&live=true' \
//   --header 'Accept: application/json' \
//   --header 'x-api-key: e6180f8a51963f3c8e694dd1ed62bba1'
