import fetch from "node-fetch";
import { LoggingLevel, smartLogging } from "./helper.js";

const fetchEbayUserToken = async (authorizationCode) => {
  smartLogging(LoggingLevel.AppTrace, `fetchEbayUserToken`);
  const clientId = process.env.EBAY_CLIENT_ID;
  const clientSecret = process.env.EBAY_CLIENT_SECRET;
  const redirectUri = process.env.EBAY_REDIRECT_URI; // Make sure this matches the URI registered with eBay
  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=authorization_code&code=${authorizationCode}&redirect_uri=${encodeURIComponent(
          redirectUri
        )}`,
      }
    );

    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();
    return data.access_token; // This is the User access token
  } catch (error) {
    smartLogging(LoggingLevel.Error,`Error fetching eBay user token: ${JSON.stringify(error)}`);
    throw error;
  }
};

export default fetchEbayUserToken;
