const express = require("express");
const cors = require("cors");
const fetch = require("node-fetch"); // Ensure you have 'node-fetch' installed
const app = express();

app.use(cors());
app.use(express.json());

const fetchToken = async () => {
  const clientID = "TylerPul-ebayimpo-PRD-a983027cf-9b6b8bba"; // Replace with your eBay App ID (Client ID)
  const clientSecret = "PRD-983027cfae51-634b-42bb-ae58-d68c"; // Replace with your eBay Cert ID (Client Secret)
  const credentials = Buffer.from(`${clientID}:${clientSecret}`).toString(
    "base64"
  );

  try {
    const response = await fetch(
      "https://api.ebay.com/identity/v1/oauth2/token",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          Authorization: `Basic ${credentials}`,
        },
        body: "grant_type=client_credentials&scope=https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope",
      }
    );

    if (!response.ok) throw new Error("Failed to fetch eBay OAuth token");

    const data = await response.json();
    return data.access_token;
  } catch (error) {
    console.error("Error fetching eBay OAuth token:", error);
    res.status(500).send("Internal Server Error");
  }
};

app.post("/submit", async (req, res) => {
  const productCode = req.body.productCode;
  const oauthToken = await fetchToken();
  console.log(productCode);
  try {
    const response = await fetch(
      `https://api.ebay.com/buy/browse/v1/item_summary/search?gtin=${productCode}`,
      {
        method: "GET",
        headers: {
          Authorization: `Bearer ${oauthToken}`,
          "Content-Type": "application/json",
        },
      }
    );
    console.log(response);
    if (!response.ok)
      throw new Error("Failed to fetch data from eBay Browse API");

    const data = await response.json();
    data.itemSummaries.forEach((item) => {
      console.log(item.price, item.condition);
    });

    res.status(200).send("Data fetched successfully");
  } catch (error) {
    console.error("Error fetching data from eBay Browse API:", error);
    res.status(500).send("Internal Server Error");
  }

  // Proceed with your logic here using the token...
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
