let linkTokenData;
let authToken;
let borrowerId;
let redirectLink;

const initializeLink = async () => {
  const linkTokenResponse = await fetch('/api/plaid/create_link_token');
  linkTokenData = await linkTokenResponse.json();
  if (linkTokenData.error) {
    document.querySelector("#startLink").innerHTML = linkTokenData.message;
    document.querySelector("#startLink").classList.remove('opacity-50');
    document.querySelector("#startLink").classList.remove('bg-green-900');
    document.querySelector("#startLink").classList.add('bg-red-600');
    document.querySelector("#startLink").removeEventListener('click', startLink);
  } else {
    document.querySelector("#startLink").classList.remove('opacity-50');
    document.querySelector("#startLink").classList.add('hover:bg-green-700');
  }
};

const getBackLink = () => {
  const url = new URL(window.location);
  const searchParams = url.searchParams;
  window.location.href = searchParams.get('redirectLink');
};

const startLink = () => {
  if (linkTokenData === undefined) {
    return;
  }

  const handler = Plaid.create({
    token: linkTokenData.link_token,
    onSuccess: async (publicToken) => await exchangeToken(publicToken, authToken, borrowerId, redirectLink),
    onExit: (err, metadata) => {
    },
    onEvent: (eventName) => {
    },
  });
  handler.open();
};

const exchangeToken = async (publicToken, authToken, borrowerId, redirectLink) => {
  const url = new URL(window.location);
  const searchParams = url.searchParams;
  authToken = searchParams.get('authorization');
  borrowerId = searchParams.get('borrowerId');
  redirectLink = searchParams.get('redirectLink');

  await fetch(
    '/api/plaid/exchange_public_token',
    {
      method: 'POST',
      headers: { 'Content-type': 'application/json' },
      body: JSON.stringify({ public_token: publicToken, authToken, borrowerId }),
    },
  );
  window.location.href = redirectLink;
}

document.querySelector("#startLink").addEventListener('click', startLink);
document.querySelector("#getBackLink").addEventListener('click', getBackLink);

initializeLink().then();
