import { ApiCardsResponse, ApiPacksResponse } from "../types/packs";
import { BASE_URL, IMAGE_BASE} from "@/constants/index";

export async function fetchPacks(brand = "packs") {
  const res = await fetch(`${BASE_URL}/api/get-packs`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ brand }),
  });

  if (!res.ok) {
    throw new Error("Failed to fetch packs");
  }

  const data: ApiPacksResponse = await res.json();
  if (data.resp !== "success") {
    throw new Error("API returned error for packs");
  }

  return data.packs.map((p) => ({
    ...p,
    image: getPackImageUrl(p.image),
  }));
}

export async function fetchCardsForPack(packId: number) {
  const res = await fetch(`${BASE_URL}/api/get-cards`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ pack: packId }),
  });

  if (!res.ok) {
    throw new Error("Failed to fetch cards");
  }

  const data: ApiCardsResponse = await res.json();

  if (data.resp !== "success") {
    throw new Error("API returned error for cards");
  }

 return data.cards.map((c) => ({
    ...c,
    image: getCardImageUrl(c.image),
  }));
}

export function getPackImageUrl(relativePath: string) {
  if (!relativePath) return "";
  if (relativePath.startsWith("http")) return relativePath;
  const img = `${IMAGE_BASE}${
    relativePath.startsWith("/") ? relativePath.replace(/^\/+/, "") : `${relativePath}`
  }`;
  return img;
}


export function getCardImageUrl(relativePath: string) {
  if (!relativePath) return "";
  if (relativePath.startsWith("http")) return relativePath;
  
  const img = `${IMAGE_BASE}${
    relativePath.startsWith("/") ? relativePath.replace(/^\/+/, "") : `${relativePath}`
  }`;
  return img;
 
}