import type { AppLocale } from '@/config/i18n';

// URL contracts also used by the translated page controls. Tests keep these
// small maps in sync with messages, without bundling both message catalogs.
export const parallelPathsParams = {
  hu: { left: 'bal', right: 'jobb', category: 'kategoria' },
  en: { left: 'left', right: 'right', category: 'category' },
} as const;

type ParallelPathsParam = keyof (typeof parallelPathsParams)['hu'];

/**
 * Reads a parallel-paths value by the page language's key, then by the other
 * language's key, so shared or bookmarked links keep their selection either way.
 */
export function getParallelPathsParam(
  get: (key: string) => string | null | undefined,
  locale: AppLocale,
  param: ParallelPathsParam
): string | null {
  const keys = [
    parallelPathsParams[locale][param],
    ...Object.values(parallelPathsParams).map((keys) => keys[param]),
  ];
  for (const key of keys) {
    const value = get(key);
    if (value) return value;
  }
  return null;
}

/** Rewrites the other language's parallel-paths keys to the page language's keys. */
export function normalizeParallelPathsQuery(query: URLSearchParams, locale: AppLocale) {
  for (const param of ['left', 'right', 'category'] as const) {
    const value = getParallelPathsParam((key) => query.get(key), locale, param);
    for (const keys of Object.values(parallelPathsParams)) query.delete(keys[param]);
    if (value) query.set(parallelPathsParams[locale][param], value);
  }
}

export const calendarViewParams = {
  hu: { single: 'napi', multi: 'idoszakos' },
  en: { single: 'daily', multi: 'periodic' },
} as const;

/** Query of an entry page, kept as-is when it redirects to its default sub-page. */
export function getRedirectQuery(
  searchParams: Record<string, string | string[] | undefined>
): Record<string, string | string[]> {
  return Object.fromEntries(
    Object.entries(searchParams).filter(
      (entry): entry is [string, string | string[]] => entry[1] !== undefined
    )
  );
}

export function getCalendarView(value: string | null): 'single' | 'multi' | undefined {
  for (const view of ['single', 'multi'] as const) {
    if (
      value === view ||
      Object.values(calendarViewParams).some((params) => params[view] === value)
    ) {
      return view;
    }
  }
}

export function getLocaleSwitchQuery(
  pathname: string,
  search: string,
  locale: AppLocale,
  nextLocale: AppLocale
): Record<string, string | string[]> {
  const query = new URLSearchParams(search);

  if (pathname === '/parhuzamos-eletutak' && locale !== nextLocale) {
    for (const key of ['left', 'right', 'category'] as const) {
      const source = parallelPathsParams[locale][key];
      const target = parallelPathsParams[nextLocale][key];
      if (!query.has(source)) continue;
      const values = query.getAll(source);
      query.delete(source);
      query.delete(target);
      values.forEach((value) => query.append(target, value));
    }
  }

  if (pathname === '/programok' || pathname === '/programok/[week]') {
    for (const key of ['nezet', 'view']) {
      if (!query.has(key)) continue;
      const values = query.getAll(key);
      query.delete(key);
      for (const value of values) {
        const view = getCalendarView(value);
        query.append(key, view ? calendarViewParams[nextLocale][view] : value);
      }
    }
  }

  return Object.fromEntries(
    [...new Set(query.keys())].map((key) => {
      const values = query.getAll(key);
      return [key, values.length === 1 ? values[0] : values];
    })
  );
}
