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

// 🌍 API Base URL

// 🎴 Brands
export type InventoryBrand = "MTG" | "Pokemon" | "Lorcana";

// ---------------------------
// 🟦 PACKS TYPES & API
// ---------------------------
export interface InventoryPack {
  id: number;
  inv_id: number;
  un_id: number;
  name: string;
  price: number;
  brand: InventoryBrand;
  image: string;
  count: number;
  token: string;
}

interface InventoryPackResponse {
  resp: string;
  packs: any[];
}

export async function fetchInventoryPacks(
  userId: string,
  token: string,
): Promise<InventoryPack[]> {
  const url = `${BASE_URL}/api/get-inventory-packs?user_id=${userId}`;

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

  const data: InventoryPackResponse = await parseJsonOrLogout(res);

  return data.packs.map((p) => {
    let image: string | null = null;

    if (p.image) {
      image = p.image.startsWith("http")
        ? p.image
        : `${IMAGE_BASE}${p.image.startsWith("/") ? p.image : `/${p.image}`}`;
    }

    return {
      ...p,
      image, // can be null safely
    };
  });
}

// ---------------------------
// 🟥 CARDS TYPES & API
// ---------------------------
export interface InventoryCard {
  id: string;
  name: string;
  price: number;
  status: string;
  rarity: string;
  probability: string;
  locked: number;
  brand: InventoryBrand;
  markup: number | null;
  pack_name: string;
  image: string;
  inv_id: number;
  count?: number;
  more?: string;
}

interface InventoryCardsResponse {
  error: string;
  resp: string;
  cards: any[];
  same: any[];
  all: any[];
  more?: string;
  offset?: number | null | undefined;
}

// POST {{base}}/api/get-inventory-cards?user_id=XXXX&is_slab=yes
export async function fetchInventoryCards(
  userId: string,
  isSlab: "yes" | "no" = "yes",
  token: string,
  offset?: number,
) {
  const url = `${BASE_URL}/api/get-inventory-cards?user_id=${encodeURIComponent(
    userId,
  )}&is_slab=${isSlab}${offset !== undefined ? `&offset=${offset}` : ""}`;

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

  const data: InventoryCardsResponse = await parseJsonOrLogout(res);

  const cards = data.cards.map(
    (c): InventoryCard => ({
      id: String(c.id),
      name: c.name,
      price: Number(c.price) || 0,
      status: c.status,
      rarity: c.rarity,
      probability: c.probability,
      locked: Number(c.locked),
      brand: c.brand,
      markup: c.markup ?? null,
      pack_name: c.pack_name,
      image: c.image?.startsWith("http")
        ? c.image
        : `${IMAGE_BASE}${
            c.image.startsWith("/") ? `${c.image.replace(/^\/+/, "")}` : c.image
          }`,
      inv_id: Number(c.inv_id),
      count: c.count ?? 1,
    }),
  );

  return {
    cards,
    offset: data.offset ?? null,
    more: data.more,
    same: data.same,
  };
}
// Sell Card

// types for sell response
interface SellCardApiCard {
  id: string;
  name: string;
  price: number;
  resp?: string;
  coins?: string;
  gems?: string;
}

export async function sellInventoryCards(
  userId: string,
  cardIds: number[],
  isSlab: "yes" | "no" = "yes", // you’re calling fetchInventoryCards(userId, "yes") so I default to "yes"
  token: string,
) {
  const url = `${BASE_URL}/api/sell-inventory-cards`;

  const payload = {
    user_id: userId,
    cards: cardIds,
    is_slab: isSlab,
  };

  const res = await fetch(url, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`, // same token you use for other inventory calls
      "Content-Type": "application/json",
    },
    body: JSON.stringify(payload),
  });

  return parseJsonOrLogout(res);
}

export async function lockInventoryCards(
  userId: string,
  cardIds: number[],
  lock: 0 | 1,
  token: string,
) {
  const url = `${BASE_URL}/api/lock-card`;

  const payload = {
    user_id: userId,
    card: cardIds, // e.g. [1553928]
    lock, // true = lock, false = unlock
  };

  const res = await fetch(url, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(payload),
  });

  return parseJsonOrLogout(res);
}

// lib/updateSession.ts
export const updateSession = async (payload: any) => {
  await fetch(`/api/auth/update`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
    credentials: "include",
  });
};
