import { IModuleClient, ModuleClientParams } from "@erp/core/client";
import { JSX } from "react";
import { RouteObject, useRoutes } from "react-router-dom";

interface ModuleRoutesProps {
  modules: IModuleClient[];
  params: ModuleClientParams;
}

interface WarpIfProtectedProps {
  component: JSX.Element;
  isProtected: boolean;
}

const WarpIfProtected = ({ component, isProtected }: WarpIfProtectedProps) => {
  return isProtected ? <>{component}</> : component;
};

export const ModuleRoutes = ({ modules, params }: ModuleRoutesProps) => {
  const routes: RouteObject[] = [];

  if (modules) {
    for (const module of modules) {
      if (typeof module.routes !== "function") {
        console.warn(`[ModuleRoutes] El módulo "${module.name}" no define una función 'routes()'`);
        continue;
      }

      const moduleRoutes = module.routes(params);

      if (!Array.isArray(moduleRoutes)) {
        console.error(
          `[ModuleRoutes] El módulo "${module.name}" debe devolver un RouteObject[], pero devolvió:`,
          moduleRoutes
        );
        continue;
      }

      const allAreRouteObjects = moduleRoutes.every(
        (r) => typeof r === "object" && r.element !== undefined
      );

      if (!allAreRouteObjects) {
        console.error(
          `[ModuleRoutes] El módulo "${module.name}" contiene elementos inválidos en su RouteObject[]`,
          moduleRoutes
        );
        continue;
      }

      routes.push(...moduleRoutes);
    }
  }

  return useRoutes(routes);
};
