// api/slab.tsx

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

type SlabCard = {
  id: number;
  card_title: string;
  card_price: number;
  cover_image: string;
  price: string; // API returns string here
};

export type SlabResponse = {
  resp: "success" | "error";
  gems?: number;
  coins?: number;
  balance?: number;
  card?: SlabCard;
  message?: string;
};

export async function buySlab(params: {
  userId: number | string;
  amount: number;
  token: string;
}) {
  const { userId, amount, token } = params;
  const url = `${BASE_URL}/api/slab?user_id=${encodeURIComponent(
    String(userId),
  )}&amount=${encodeURIComponent(String(amount))}`;
  const res = await fetch(url, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      Accept: "application/json",
    },
    cache: "no-store",
  });
  console.log("eres of byy", res);
  return parseJsonOrLogout(res);
}

export async function fetchSlabAnalytics(token: any, amount: any) {
  const url = `${BASE_URL}/api/get-slab?amount=${encodeURIComponent(amount)}`;

  const res = await fetch(url, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      Accept: "application/json",
    },
  });

  return parseJsonOrLogout(res);
}

export async function fetchSlab(userId: any, token: any, amount: any) {
  const url = `${BASE_URL}/api/slab?user_id=${userId}&amount=${encodeURIComponent(amount)}`;

  const res = await fetch(url, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      Accept: "application/json",
    },
  });

  return parseJsonOrLogout(res);
}

export async function getSlabHistory(user_id: string, token: string) {
  try {
    const res = await fetch(`${BASE_URL}/api/slab-history`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({ user_id }),
    });

    return parseJsonOrLogout(res);
  } catch (e) {
    throw e;
  }
}
