import {
  getIsOptionManifest, getIsBackgroundpManifest, getIsContentpManifest, getIsPopupManifest,
} from '@/config/get';
import { loggerPlugin } from '@/plugins/logger';

/** @type {BridgeApi} */
let bridgeApi = null;

/** @type {BridgeContextType} */
let bridgeContext = '';

export const getBridgeApi = async () => {
  if (bridgeApi) {
    return bridgeApi;
  }

  if (getIsOptionManifest() || getIsPopupManifest()) {
    if (window.location.pathname.includes('popup')) {
      bridgeContext = 'popup';
      bridgeApi = await import('webext-bridge/popup');
    } else {
      bridgeContext = 'options';
      bridgeApi = await import('webext-bridge/options');
    }
  } else if (getIsBackgroundpManifest()) {
    bridgeContext = 'background';
    bridgeApi = await import('webext-bridge/background');
  } else if (getIsContentpManifest()) {
    bridgeContext = 'content-script';
    bridgeApi = await import('webext-bridge/content-script');
  }

  if (!bridgeApi) {
    throw 'GET_BRIDGE_ERROR';
  }

  loggerPlugin.info({
    msg: 'BRIDGE_CONTEXT',
    bridgeContext,
  });

  return bridgeApi;
};

export { bridgeContext, bridgeApi };
