type SearchParamsLike = {
  get: (name: string) => string | null;
};

const EXPENSE_LIST_PATH = '/expense';

export const getExpenseListReturnTo = (searchParams: SearchParamsLike) => {
  const existingReturnTo = searchParams.get('returnTo');

  if (existingReturnTo?.startsWith(EXPENSE_LIST_PATH)) {
    return existingReturnTo;
  }

  const params = new URLSearchParams();
  const page = searchParams.get('page');
  const limit = searchParams.get('limit');

  if (page) params.set('page', page);
  if (limit) params.set('limit', limit);

  const queryString = params.toString();

  return queryString
    ? `${EXPENSE_LIST_PATH}?${queryString}`
    : EXPENSE_LIST_PATH;
};

export const buildExpenseActionHref = (
  path: string,
  expenseId: number | string,
  searchParams: SearchParamsLike
) => {
  const params = new URLSearchParams({
    expenseId: String(expenseId),
    returnTo: getExpenseListReturnTo(searchParams),
  });

  return `${path}?${params.toString()}`;
};
