import { loggerBackground } from '@/plugins/logger';
import {
  storageUserToken,
  storageShopeeShopId,
  storageTiktokShopId,
  storageLazadaShopId,
} from '@/plugins/storage/items';
import { shopeeShopIdentify } from '@background/shopee';
import { tiktokShopIdentify } from '@background/tiktok';
import { lazadaShopIdentify } from '@background/lazada';

export const storageWatchService = () => {
  storageUserToken.watch((newToken, oldToken) => {
    if (newToken === oldToken) {
      return;
    }

    loggerBackground.log({
      msg: 'STORAGE_WATCH_USER_TOKEN_CHANGED',
      hasToken: !!newToken,
    });
  });

  storageShopeeShopId.watch((newShopId, oldShopId) => {
    if (!newShopId || newShopId === oldShopId) {
      return;
    }

    loggerBackground.log({
      msg: 'STORAGE_WATCH_SHOPEE_SHOP_CHANGED',
      newShopId,
    });

    shopeeShopIdentify().catch((error) => {
      loggerBackground.error({
        msg: 'STORAGE_WATCH_SHOPEE_IDENTIFY_ERROR',
        error,
      });
    });
  });

  storageTiktokShopId.watch((newShopId, oldShopId) => {
    if (!newShopId || newShopId === oldShopId) {
      return;
    }

    loggerBackground.log({
      msg: 'STORAGE_WATCH_TIKTOK_SHOP_CHANGED',
      newShopId,
    });

    tiktokShopIdentify().catch((error) => {
      loggerBackground.error({
        msg: 'STORAGE_WATCH_TIKTOK_IDENTIFY_ERROR',
        error,
      });
    });
  });

  storageLazadaShopId.watch((newShopId, oldShopId) => {
    if (!newShopId || newShopId === oldShopId) {
      return;
    }

    loggerBackground.log({
      msg: 'STORAGE_WATCH_LAZADA_SHOP_CHANGED',
      newShopId,
    });

    lazadaShopIdentify().catch((error) => {
      loggerBackground.error({
        msg: 'STORAGE_WATCH_LAZADA_IDENTIFY_ERROR',
        error,
      });
    });
  });
};
