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

export interface UpdateTradePayload {
  user_id: string;
  id: number;
  prices: number;
  brand: string;
  token: string;
}

export interface UpdateTradeResponse {
  resp: string;
  msg?: string;
  cards?: {
    id: number;
    pack: string;
    name: string;
    brand: string;
    rarity: string;
    probability: string;
    price: number;
    date: number;
    image: string;
  }[];
}

export async function updateTradePrice(
  payload: UpdateTradePayload,
): Promise<UpdateTradeResponse> {
  const res = await fetch(`${BASE_URL}/api/update-trade`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${payload.token}`,
    },
    body: JSON.stringify(payload),
  });

  const data = (await res.json()) as UpdateTradeResponse;

  if (!res.ok ) {
    forceLogout();
    throw new Error("Failed to update trade price");
  }

  return data;
}

export interface SaveTradePayload {
  user_id: string;
  cards: { inv_id: number; price: number }[];
  token: string;
}

export interface SaveTradeResponse {
  resp: string;
  msg?: string;
  cards?: {
    id: number;
    pack: string;
    name: string;
    brand: string;
    rarity: string;
    probability: string;
    price: number;
    date: number;
    image: string;
  }[];
}

export async function saveTrade(
  payload: SaveTradePayload,
): Promise<SaveTradeResponse> {
  const res = await fetch(`${BASE_URL}/api/save-trade`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${payload.token}`,
    },
    body: JSON.stringify(payload),
  });

  const data = (await res.json()) as SaveTradeResponse;

  if (!res.ok ) {
    forceLogout();
    throw new Error("Failed to save trade");
  }

  return data;
}

export async function deleteTrade(payload: {
  user_id: string;
  id: number;
  token: string;
}): Promise<{ resp: string; msg?: string }> {
  const res = await fetch(`${BASE_URL}/api/delete-trade`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${payload.token}`,
    },
    body: JSON.stringify(payload),
  });
  const data = await res.json();

  if (!res.ok ) {
    forceLogout();
    throw new Error("Failed to delete trade");
  }

  return data;
}
