// api/trade.ts
import { BASE_URL, forceLogout, parseJsonOrLogout } from "@/constants/index";

export type TradeApiCard = {
  id: number;
  pack: string;
  name: string;
  brand: string;
  rarity: string;
  probability: string;
  price: number;
  date: number;
  image: string;
  user_name: string;
  user_image: string | Record<string, never>;
  user_id: string;
};

export type TradeApiResponse = {
  resp: string;
  cards: TradeApiCard[];
  total: number;
};

export interface BuyTradePayload {
  user_id: string;
  cards: number[];
  brand: string;
  action: "buy-trade";
}

export interface BuyTradeResponse {
  resp: "success" | "error";
  message?: string;
}

export async function getTradeCards(brand: string): Promise<TradeApiResponse> {
  const res = await fetch(`${BASE_URL}/api/get-trade`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      // Authorization: `Bearer ${token}`,
    },

    body: JSON.stringify({ brand }),
    cache: "no-store",
  });

  return parseJsonOrLogout(res);
}

// app/lib/api/trade.ts

export const buyOneTrade = async (
  userId: string,
  tradeCardId: number,
  cards: Array<number | string>,
  token: string,
) => {
  const qs = new URLSearchParams();
  qs.set("user_id", userId);
  qs.set("trad_card", String(tradeCardId));
  qs.set("cards", `[${cards.join(",")}]`);

  const res = await fetch(`${BASE_URL}/api/buy-one-trade?${qs.toString()}`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      Accept: "application/json",
    },
  });

  return parseJsonOrLogout(res);
};

export async function fetchHomeMarket() {
  const res = await fetch(`${BASE_URL}/api/get-home-market`, {
    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 games (${res.status})`);
  }
  return data;
}
