/* eslint-disable @typescript-eslint/no-use-before-define */
import { useAtomValue } from 'jotai';
import { OrgShortName } from 'src/application/models';
import { orgShortNameAtom } from 'src/atoms/envive/enviveConfig';

abstract class ImageResolver {
  abstract resolve(url: string, size: number): string;
}

class MerchantImageResolver {
  private static imageResolverMap = new Map<string, ImageResolver>();

  private static loadMapping() {
    if (this.imageResolverMap.size === 0) {
      this.imageResolverMap.set(OrgShortName.Spanx, new ShopifyImageResolver());
      this.imageResolverMap.set(OrgShortName.SpanxStaging, new ShopifyImageResolver());
      this.imageResolverMap.set(OrgShortName.UniqueVintage, new ShopifyImageResolver());
    }
    return this.imageResolverMap;
  }

  static get(name: string) {
    return this.loadMapping().get(name);
  }
}

class ShopifyImageResolver extends ImageResolver {
  resolve(url: string, size: number): string {
    const pattern = /_\d+x\.jpg/;
    const urlHasPrefix = pattern.test(url);
    const newSizePrefix = `_${size}x.jpg`;
    if (urlHasPrefix) {
      return url.replace(pattern, newSizePrefix);
    }
    return url.replace('.jpg', newSizePrefix);
  }
}

export const useImageResolver = () => {
  const orgShortName = useAtomValue(orgShortNameAtom);
  const resolve = (image?: string, size?: number) => {
    if (image && size && orgShortName) {
      const newImagePath = MerchantImageResolver.get(orgShortName)?.resolve(image, size);
      return newImagePath || image;
    }
    return image;
  };

  return {
    resolve,
  };
};
