import type { SearchKeywordOption } from '../../components/search';
import type { SearchOpenMode } from '../../layer/search/types';

const RECENT_SEARCH_OPTION_IDS_STORAGE_KEY_PREFIX = 'work-app.search.recent-option-ids';
const MAX_RECENT_SEARCH_OPTIONS = 5;

function resolveStorageKey(mode: SearchOpenMode) {
  return `${RECENT_SEARCH_OPTION_IDS_STORAGE_KEY_PREFIX}.${mode}`;
}

function readStorageValue(mode: SearchOpenMode) {
  if (typeof window === 'undefined') {
    return [];
  }

  try {
    const rawValue = window.localStorage.getItem(resolveStorageKey(mode));
    const parsed = rawValue ? JSON.parse(rawValue) : [];
    return Array.isArray(parsed) ? parsed.filter((value): value is string => typeof value === 'string' && value.trim().length > 0) : [];
  } catch {
    return [];
  }
}

export function pushRecentSearchOption(optionId: string, mode: SearchOpenMode) {
  if (typeof window === 'undefined') {
    return;
  }

  const normalizedOptionId = optionId.trim();

  if (!normalizedOptionId) {
    return;
  }

  const nextIds = [normalizedOptionId, ...readStorageValue(mode).filter((value) => value !== normalizedOptionId)].slice(
    0,
    MAX_RECENT_SEARCH_OPTIONS,
  );

  try {
    window.localStorage.setItem(resolveStorageKey(mode), JSON.stringify(nextIds));
  } catch {
    // ignore local storage quota or privacy errors
  }
}

export function resolveRecentSearchOptions(options: SearchKeywordOption[], mode: SearchOpenMode) {
  const optionMap = new Map(options.map((option) => [option.id, option]));
  return readStorageValue(mode)
    .map((optionId) => optionMap.get(optionId) ?? null)
    .filter((option): option is SearchKeywordOption => option !== null);
}
