import { Navigate } from 'react-router-dom';

import { profileRoutes } from 'src/pages/dashboard/profile/routes';
import { type MeUser } from 'src/types/user';
import { hasAnyPermissions, type UserPermissions } from 'src/utils/permissions';

type Routes = {
  path?: string;
  element?: JSX.Element;
  index?: boolean;
  children?: Routes[];
  defaultPathIf?: UserPermissions[];
};

export const getDefaultRoute = (
  routes: Routes,
  permissions: string[],
  user?: MeUser | null,
) => {
  if (!user) {
    return {
      path: '/',
      element: <Navigate to="/" />,
      defaultPathIf: [],
    };
  }

  const invalidDefaults = ['profile', 'library', 'microloans'];

  const rawPath =
    routes.children?.find(
      child =>
        child.defaultPathIf?.length &&
        hasAnyPermissions(permissions, child.defaultPathIf),
    )?.path || '';

  const path = rawPath.replace(/\/\*$/, ''); // TODO-[Dolphin]: strip splat for invalidDefaults match. Remove with legacy libraries.

  const defaultPath = invalidDefaults.includes(path)
    ? profileRoutes.profile(user.id)
    : path;

  return {
    path: '/',
    element: <Navigate to={defaultPath} />,
    defaultPathIf: [],
  };
};
