import fetch from "node-fetch";
import fetchEbayUserToken from "../utils/fetchEbayUserToken.js"; 

export const addItem = async (req, res) => {
  const itemDetails = req.body;
  // must be called with req/res due to cookie access - cookie flow is inside fetchEbayUserToken()
  const token = await fetchEbayUserToken(req, res)

  // Constructing the payload for the Inventory API
  const offerPayload = {
    sku: itemDetails.sku,
    marketplaceId: itemDetails.marketplaceId,
    format: itemDetails.format,
    listingDescription: itemDetails.listingDescription,
    availableQuantity: itemDetails.availableQuantity,
    categoryId: itemDetails.categoryId,
    listingPolicies: {
      paymentPolicyId: itemDetails.listingPolicies.paymentPolicyId,
      fulfillmentPolicyId: itemDetails.listingPolicies.fulfillmentPolicyId,
      returnPolicyId: itemDetails.listingPolicies.returnPolicyId,
    },
    pricingSummary: {
      price: {
        currency: itemDetails.pricingSummary.price.currency,
        value: itemDetails.pricingSummary.price.value,
      },
    },
    merchantLocationKey: itemDetails.merchantLocationKey,
    quantityLimitPerBuyer: itemDetails.quantityLimitPerBuyer,
  };

  try {
    const response = await fetch(
      "https://api.ebay.com/sell/inventory/v1/offer",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Content-Language": "en-US",
          "Authorization": `Bearer ${token}`,
        },
        body: JSON.stringify(offerPayload),
      }
    );
    
      console.log(response)
if (!response.ok) {
  const errorBody = await response.text(); // Get the response body as text
  console.error(`eBay API responded with status ${response.status}: ${errorBody}`);
  throw new Error(`eBay API responded with status ${response.status}: ${errorBody}`);
}


    const responseData = await response.json();
    res.json({ success: true, data: responseData });
  } catch (error) {
    console.error("Error adding item to eBay via Inventory API:", error);
    console.log(error.message);
    res.status(500).json({
      success: false,
      message: "Failed to add item to eBay via Inventory API",
      error: error.message,
    });
  }
};
