import { parse, stringify } from 'qs';

import { USER_PREFERENCES } from '../constants';

import { ContentOwnerType } from '@/modules/@common/user/types';

import { getStorageItem, removeStorageItem, setBrowserStorageItem } from '@/modules/@common/storage/helpers';

export const removeUser = () => {
  removeStorageItem(USER_PREFERENCES);
};

export const setUser = (token: string) => {
  const postData = {
    type: 'ac_editor_login',
    token,
  };

  if (typeof window !== 'undefined') {
    window.parent.postMessage(postData, '*');
  }
};

//----------------------

export const hasPermission = (permission: string, permissions: string[]) => permissions.includes(permission);

export const isOwnContent = (contentOwnerId: string, userContentOwners: ContentOwnerType[]) =>
  userContentOwners.some((item) => item.contentOwnerId === contentOwnerId && item.publisherOwnsContent);

export const getUserPreferences = () => JSON.parse(getStorageItem(USER_PREFERENCES) as string);

export const setUserPreferences = (nameSpace: string, params: { [key: string]: string }) => {
  const preferences = getUserPreferences();
  setBrowserStorageItem(
    USER_PREFERENCES,
    JSON.stringify({
      ...preferences,
      [nameSpace]: params,
    }),
  );
};

const getUrl = (pathname: string, search: string, hash: string) => {
  const url = parse(search, { ignoreQueryPrefix: true });

  delete url.token;

  const questionMark = stringify(url) ? '?' : '';

  return `${pathname}${questionMark}${stringify(url)}${hash}`;
};

export const getUserRedirectUrl = () => {
  const { pathname, search, hash } = window.location;

  return pathname === '/' ? '/' : getUrl(pathname, search, hash);
};
