import {compare} from 'compare-versions';
import {FeatureDeprecatedError, Shopify} from '@shopify/shopify-api';

import {SHOPIFY_REACT_ROUTER_LIBRARY_VERSION} from './version';

// eslint-disable-next-line no-warning-comments
// TODO This has been copied from shopify-app-express, it should be extracted into a shared package
// https://github.com/orgs/Shopify/projects/6899/views/1?pane=issue&itemId=28358070
export function overrideLogger(logger: Shopify['logger']): Shopify['logger'] {
  const baseContext = {package: 'shopify-app'};

  const warningFunction: Shopify['logger']['warning'] = (
    message,
    context = {},
  ) => logger.warning(message, {...baseContext, ...context});

  function deprecated(warningFunction: Shopify['logger']['warning']) {
    return function (version: string, message: string): Promise<void> {
      if (compare(SHOPIFY_REACT_ROUTER_LIBRARY_VERSION, version, '>=')) {
        throw new FeatureDeprecatedError(
          `Feature was deprecated in version ${version}`,
        );
      }

      return warningFunction(`[Deprecated | ${version}] ${message}`);
    };
  }

  return {
    ...logger,
    log: (severity, message, context = {}) =>
      logger.log(severity, message, {...baseContext, ...context}),
    debug: (message, context = {}) =>
      logger.debug(message, {...baseContext, ...context}),
    info: (message, context = {}) =>
      logger.info(message, {...baseContext, ...context}),
    warning: warningFunction,
    error: (message, context = {}) =>
      logger.error(message, {...baseContext, ...context}),
    deprecated: deprecated(warningFunction),
  };
}
