import { loggerBackground } from '@/plugins/logger';
import socketAppConnect from './app';
import socketWorkerConnect from './worker';
import { storageUseShopManager, storageWorkerFetchService } from '@/plugins/storage/items';
import { getConfigService } from '../get';

export const socketService = async () => {
  const isUseShopManager = await storageUseShopManager.getValue();
  const isWorkerFetchService = await storageWorkerFetchService.getValue();

  const configService = await getConfigService();

  if (configService.connectApp) {
    socketAppConnect().then(() => {
      loggerBackground.info({
        msg: 'SOCKET_APP_CONNECT',
      });
    }).catch((error) => {
      loggerBackground.error({
        msg: 'SOCKET_APP_ERROR',
        error,
      });
    });
  }

  if (!isUseShopManager && isWorkerFetchService && configService.fetchUrl) {
    socketWorkerConnect(true).then(() => {
      loggerBackground.info({
        msg: 'SOCKET_WORKER_CONNECT',
      });
    }).catch((error) => {
      loggerBackground.error({
        msg: 'SOCKET_WORKER_ERROR',
        error,
      });
    });
  } else {
    loggerBackground.info({
      msg: 'SOCKET_WORKER_SKIP',
    });
  }
};
