import { MessageRole, ProductSearchMessageMetadata } from '../models/message';

export const parseHref = (
  href: string,
): { url: URL | undefined; urlSearchParams: URLSearchParams | undefined } => {
  try {
    const url = new URL(href);
    const urlSearchParams = new URLSearchParams(url.search);
    return { url, urlSearchParams };
  } catch (e) {
    return { url: undefined, urlSearchParams: undefined };
  }
};

export const createUrlWithQueryParams = (
  url: string,
  queryParams: Record<string, string>,
): string => {
  const urlObj = new URL(url, window.location.href);
  Object.entries(queryParams).forEach(([value, key]) => urlObj.searchParams.append(value, key));

  return urlObj.href;
};

export const getQueryParam = (key: string): string | null => {
  const urlObj = new URL(window.location.href);
  return urlObj.searchParams.get(key);
};

type SearchMessage = {
  id: string;
  role: MessageRole;
  createdAt: string;
} & ProductSearchMessageMetadata;

export const buildSearchHash = (message: SearchMessage): string =>
  `#evs=true&s=${message.id}&q=${message.metadata.generatedQuery}`;

export const buildSearchStartHash = (query: string): string => `#evs=true&q=${query}`;

// Basic parser for the search hash
export const parseSearchHash = (hash: string): { id: string | null; query: string | null } => {
  if (!hash.startsWith('#evs=true')) {
    return { id: null, query: null };
  }
  const params = Object.fromEntries(hash.split('&').map(param => param.split('=')));
  return {
    id: params.s ? decodeURIComponent(params.s) : null,
    query: params.q ? decodeURIComponent(params.q) : null,
  };
};

window.history.pushState(null, '');
