// app/lib/api/coinFlip.ts

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

export type FlipApiGame = {
  game_id: number;
  plyaer1: { name: string; image: string }; // backend typo: "plyaer1"
  price: number | string; // backend might return long float as string
  cards: string[];
};

export type FlipApiResponse = {
  resp: "success" | "error";
  data: FlipApiGame[];
  message?: string;
};

export async function getFlipGames(token?: string) {
  const res = await fetch(`${BASE_URL}/api/get-flip`, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
    cache: "no-store",
  });

  return parseJsonOrLogout(res);
}

export type CreateFlipResponse = {
  resp: "success" | "error";
  message?: string;
  data?: any;
  game_id: number;
};

export async function createFlipGame(params: {
  userId: string;
  cards: Array<number | string>;
  token: string;
}) {
  const { userId, cards, token } = params;

  // backend expects query param cards=[23]
  const cardsParam = encodeURIComponent(JSON.stringify(cards));

  const url = `${BASE_URL}/api/create-flip?user_id=${encodeURIComponent(
    userId,
  )}&cards=${cardsParam}`;

  const res = await fetch(url, {
    method: "POST", // backend is GET (even though create should ideally be POST)
    headers: {
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
    cache: "no-store",
  });
  return parseJsonOrLogout(res);
}

export type JoinFlipResponse =
  | { resp: "success"; data: any; message?: string }
  | { resp: "error"; data?: any; message?: string };

export async function joinFlipGame(params: {
  userId: string;
  gameId: number | string;
  cards: Array<number | string>;
  token: string;
}) {
  const { userId, gameId, cards, token } = params;

  const cardsParam = encodeURIComponent(JSON.stringify(cards));
  const url = `${BASE_URL}/api/join-flip?user_id=${encodeURIComponent(
    userId,
  )}&cards=${cardsParam}&game_id=${encodeURIComponent(String(gameId))}`;

  const res = await fetch(url, {
    method: "POST",
    headers: {
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
    cache: "no-store",
  });

  return parseJsonOrLogout(res);
}

export async function getFlipHistory(user_id: string, token: string) {
  try {

    const res = await fetch(`${BASE_URL}/api/flip-history?user_id=${user_id}`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({ user_id }),
    });
    return parseJsonOrLogout(res);
  } catch (e: any) {
    throw e;
  }
}
 