import fetch from "node-fetch";

const fetchEbayUserToken = async (req, res) => {
  const ebayClientId = process.env.EBAY_CLIENT_ID;
  const ebayClientSecret = process.env.EBAY_CLIENT_SECRET;
  const refreshToken = process.env.EBAY_REFRESH_TOKEN; // This is retrieved from a manual process
  const credentials = Buffer.from(`${ebayClientId}:${ebayClientSecret}`).toString("base64");
  const scopes = encodeURIComponent([
    "https://api.ebay.com/oauth/api_scope",
    "https://api.ebay.com/oauth/api_scope/sell.marketing.readonly",
    "https://api.ebay.com/oauth/api_scope/sell.marketing",
    "https://api.ebay.com/oauth/api_scope/sell.inventory.readonly",
    "https://api.ebay.com/oauth/api_scope/sell.inventory",
    "https://api.ebay.com/oauth/api_scope/sell.account.readonly",
    "https://api.ebay.com/oauth/api_scope/sell.account",
    "https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly",
    "https://api.ebay.com/oauth/api_scope/sell.fulfillment",
    "https://api.ebay.com/oauth/api_scope/sell.analytics.readonly",
    "https://api.ebay.com/oauth/api_scope/sell.finances",
    "https://api.ebay.com/oauth/api_scope/sell.payment.dispute",
    "https://api.ebay.com/oauth/api_scope/commerce.identity.readonly",
    "https://api.ebay.com/oauth/api_scope/sell.reputation",
    "https://api.ebay.com/oauth/api_scope/sell.reputation.readonly",
    "https://api.ebay.com/oauth/api_scope/commerce.notification.subscription",
    "https://api.ebay.com/oauth/api_scope/commerce.notification.subscription.readonly",
    "https://api.ebay.com/oauth/api_scope/sell.stores",
    "https://api.ebay.com/oauth/api_scope/sell.stores.readonly"
  ].join(' '));

  const token = req.cookies.ebayUserToken;
  const tokenExpiry = req.cookies.ebayUserTokenExpiry ? new Date(req.cookies.ebayUserTokenExpiry) : null;

  // Check if the token exists and is not expired
  if (token && tokenExpiry && new Date() < tokenExpiry) {
    return token; // Token is valid, use it
  }

  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=refresh_token&refresh_token=${refreshToken}&scope=${scopes}`,
    });

    if (!response.ok) {
      const errorBody = await response.text();
      throw new Error(`Failed to fetch eBay user token: ${response.status} ${response.statusText} - ${errorBody}`);
    }

    const data = await response.json();
    const expiryDuration = 1.92 * 60 * 60 * 1000; // 1 hour 55 minutes in milliseconds

    // Store the new token in an HTTP-only cookie
    res.cookie('ebayUserToken', data.access_token, { httpOnly: true, maxAge: expiryDuration });

    return data.access_token;
  } catch (error) {
    console.error("Error fetching eBay user token:", error);
    throw error;
  }
};

export default fetchEbayUserToken