import { beforeUnloadHandler } from "../app.js";

 async function getJSONData(response) {
  if (response.status === 420) {
    window.removeEventListener("beforeunload", beforeUnloadHandler);
    window.location.replace("/");
  }
  if (!response.ok) {
    const errorData = await response.json()
    throw new Error(errorData.message || `Error del servidor: ${response.status}`);
  }
  const data = await response.json();
  return data.data;
}

async function sendOrder(order, token) {
  try {
    const response = await fetch("/api/orders/send", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`
      },
      body: JSON.stringify(order)
    });
    return await getJSONData(response);
  } catch (error) {
    console.error("Error al enviar la orden:", error);
    throw error;
  }
}

export async function freeBeer(token, tableNumber) {
  try {
    const response = await fetch("/api/users/reward", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`
      },
      body: JSON.stringify({ tableNumber })
    });
    return await getJSONData(response);

  } catch (error) {
    console.error("Error al obtener cerveza gratis:", error);
    throw error;
  }
}

async function getProducts(token){
  const response = await fetch("/api/products?status=1", {
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${token}`
    }
  });
  
  const data = await getJSONData(response);
  data.products.map(product => {
    if (product.promotion) {
      product.price = product.promotion.price;
    }
  })
  return data.products;
}


export {sendOrder, getProducts}